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.
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.
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.
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