0

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?)

IpsRich
  • 797
  • 10
  • 23

4 Answers4

3

You can use ternary operators:

var a = false ? 123 : true ? 456 : 789;
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • Thanks, I would usually use the ternary operator, but my question is specifically about the `if` statement. – IpsRich Oct 22 '13 at 11:38
0

have as a function instead:

function a(b) //where b is your boolean
{
   if(b)
   {
      return 123;
   }
   else
   {
      return 456;
   }
}
Savv
  • 433
  • 2
  • 7
0

Use a ternary operator: var x = (true ? 432 : 765); // will set x to 432

See also JavaScript ternary operator example with functions

Community
  • 1
  • 1
steenbergh
  • 1,642
  • 3
  • 22
  • 40
0

Use function instead of directly using that expression. And then you also have to return those values.

 
var a=function(){if (false) { return 123; } else if (true) { return 456; } else { return 789; }}
alert(a());
swapnil
  • 1
  • 3