Can I write the if else
shorthand without the else
?
var x=1;
x==2 ? dosomething() : doNothingButContinueCode();
I've noticed putting null
for the else works (but I have no idea why or if that's a good idea).
Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.
var | var
syntax. Careful as it's potentially difficult to "see", especially (IMO) ternaries being problematic. Use sparingly. – Countermark:)
– Countermarkfoo = bar | cat;
, where if the first is false? null?, it "falls through" to the second. I've only seen it, though, and don't use it. – Countermarka || b
ora && b
, otherwiseb
will always be evaluated. – Ellsworthif
statements more readable/parse in a scan of the page. But I'm sure others disagree. – CountermarkXOR
? – Countermarka != b
ora ^ b
. Both a and b will need to be evaluated, xor doesn't have short-circuiting. – EllsworthXOR
gets my goat. I think theXOR
wizard's been feeding it, too. Still a mystery what it does in practice logically. – Countermarkvar a = b || c
? – Countermarkcondition && (codetorun)
they way it works is that && returns true only if both are true. So if condition is true, it goes to second which is in brackets so it computes that first, run it. then return true/false. But we are only concerned with act of running. So when it's condition is false, it just returns false as there is no need to evaluate 2nd statement as result will be false. – Cuprumstatement || statement
on the other side will run first one and then second. if first is false; so opposite of&&
.||
returns if only one is true, so if first statement is false, the second will be evaluated if in brackets then run, and returned. – Cuprum