I was screwing around with Google's JavaScript compiler, and going over the code it outputs, when I realized something odd. I was trying to figure out how it worked, when it hit me.
So, here goes.
As you may know, if you do:
if (test && test2 && test3) alert("all three!");
Each condition is tested separately. If test is false, then it doesn't bother checking test2 or test3.
If test is true and test2 is false, it doesn't bother checking test3.
Knowing this, you can get rid of this if statement entirely.
Entire code:
test && test2 && test3 && alert("all three!");
Parsed, this is the same as putting:
true;
It returns true, but it does nothing with it, so nothing is output or noticed.
It tests whether or not test, test2, test3, and alert() are true. alert() is always true, but it wouldn't matter anyway, since it's the last thing called. true; and false; have the same effect (nothing). What matters is whether or not the first three are true.
So, in the mind of JavaScript:
test && test2 && test3 && alert("all three!");
Is test true?
N: stop testing the rest
Y: is test2 true?
N: stop testing the rest
Y: is test3 true?
N: stop testing the rest
Y: is alert("all three!") true? // this will actually alert the message
N: return false
Y: return true // doesn't matter, 'cause the returned value is ignored
My previous code:
if (this.getAttribute("value")=="Search") this.setAttribute("value","");
Compressed code:
this.getAttribute("value")=="Search"&&this.setAttr ibute("value","");
Hope this is helpful. Not exactly standards, but it apparently works cross-browser enough for Google to use it. I don't plan on changing my code to do this (i.e. when I make it), but I do plan on using their compressed code for public scripts. Just figured you guys would love the nerdom within it.
Results 1 to 1 of 1
- 09 Dec. 2009 05:57am #1
JavaScript: get rid of some if statements