Before going on to the next thought we should apply the principals from the last post to ternaries:
Simply, just as
if(val = true) alert(val);
first sets val to true, than evaluates 'val' [and calls the alert].
Similarly,
(val = true) ? alert('val') : null;
also sets val to true, and than evaluates val [and calls the alert].
However, this leads us into an interesting scenario (which has tripped up many a developer) which should be better explained.
In JS & related languages, the ternary can be used to assign a value as well as to run functions. So that the following are both legal, and both assign "less" to val:
var val = (5<6 ? "less" : "more");
(5 < 6) ? val = "less" : val = "more";
It is usually pretty clear which statement it should calculate, but not always:
main = false ? val = 0 : val = 1;
Watch out there - I didn't use two equals (main == true)! We are not evaluating main, we are assigning it a value!
This can mean either:
(main = false) ? val = 0 : val = 1;
ie:
if (main = false) val = 0;
else val = 1;
which will first assign false to main, then will evaluate main, and run the second half of the function, which assigns 1 to val
Or:
main = (false ? val = 0 : val = 1);
ie:
main = (
if(false) val = 0;
else val = 1;
)
which will evaluate the false, and assign 1 to val, than assign val to main, in which case they both become 1.
The answer is.......
The second way: which results in main = val = 1!
Unless clearly evaluating a statement, it will assume that it is setting a value.
Once at it:
val1 = val2 = false ? val = 0 : val = 1;
is the same as: val1 = (val2 = (false ? val = 0 : val = 1));
Which obviously will translate with all the values being equal to 1.
And the following if will run conditional and alert "1". (main = val = 1):
if (main = false ? val = 0 : val = 1;) alert (main) ;
Whereas if we would put the condition in parenthesis it will run, but will alert "false":
if ((main = false) ? val = 0 : val = 1;) alert (main) ;
It will still run, since by the time it has finished dealing with the ternary it's as though it says:
if (val = 1;) alert (main) ;
or even if (val) alert(main);
However, main is set to false in the midst of the assigning.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment