-1
var x = 10;


var b = if(x>5){return true};

console.log(b);

I'm not getting why this is incorrect and will give an error.

Pointy
  • 405,095
  • 59
  • 585
  • 614
ritik jain
  • 13
  • 4
  • Related: [setting a javascript variable with an if statement -- should the 'var = x' be inside or outside the IF?](https://stackoverflow.com/q/31971801) – VLAZ Mar 27 '22 at 13:16

2 Answers2

2

The syntax of a variable initializer stipulates that it must be an expression. An if statement is not an expression.

You can write

var b = (x > 5) ? true : undefined;

(or whatever you want b to be when x is not greater than 5). That ? : expression is an expression, so it works as the initializer part of the declaration.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

You can use this solution

var x = 10;

var b =  x>5? true:false
# if the condition (x>5) is true. 
# will execute the first return(true) 
# or else the second return will execute (false) 


console.log(b) #Output= true