If you enter the following into Firefox's Browser Console, the result is 456
:
if (false) { 123; } else if (true) { 456; } else { 789; }
If you adjust the true
/false
combinations, you can also get 123
or 789
as a result. However, if you try and do something like:
var a = if (false) { 123; } else if (true) { 456; } else { 789; };
you just get a syntax error. The syntax error doesn't surprise me, but I'm wondering what the point is of if
statements having a value if that value can't be used.
So my question is: can an if
statement be used as an expression, and if so, how?
EDIT: Thanks for the responses so far, but just to be absolutely clear, I know I could use functions and/or the ternary operator to achieve what I've described, but I specifically want to know whether the 'return value' of an if
statement can be used, i.e. whether an if
statement can be used as an expression. I'm not asking for alternative ways of setting a value based upon various conditions.
(And if an if
cannot be used as an expression, then why does Firefox's Browser Console show a value for the first example above?)