I was surfing on the web in search of a shorthand Javascript notation for an if-statement. ONLY the if, not the else. My question: does it exist? eg:
(i === 0) ? onlyMyTrueValue;
The only snippet I seem to find is this one:
(i === 0) ? myTrueValue : myFalseValue;
I was surfing on the web in search of a shorthand Javascript notation for an if-statement. ONLY the if, not the else. My question: does it exist? eg:
(i === 0) ? onlyMyTrueValue;
The only snippet I seem to find is this one:
(i === 0) ? myTrueValue : myFalseValue;
Share
Improve this question
edited Sep 4, 2014 at 15:17
Pablo Matias Gomez
6,8137 gold badges40 silver badges74 bronze badges
asked May 20, 2013 at 16:13
user2381011user2381011
3516 silver badges21 bronze badges
2
|
2 Answers
Reset to default 14You can do:
(i === 0) && onlyMyTrueValue;
The right hand side of the above statement will execute only if the left hand side passes.
You could do (i === 0) && onlyMyTrueValue;
, but you shouldn't, for readability sake.
Compare your original:
(i === 0) ? onlyMyTrueValue;
And plain old if:
if (i === 0) onlyMyTrueValue;
That's only one more character, and an identical number of characters to the &&
method. Go with the readable choice.
if
statement isif(i===0)somevar=someval;
but you should let a JS minifier handle that. – zzzzBov Commented May 20, 2013 at 16:15