How does the below code execute?
if(a=2 && (b=8))
{
console.log(a)
}
OUTPUT
a=8
Should you define a variable inside IF statement? Honestly, there's no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.
Yes, you can assign the value of variable inside if.
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)
The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?
It has nothing to do with the if
statement, but:
if(a=2 && (b=8))
Here the last one, (b=8)
, actually returns 8 as assigning always returns the assigned value, so it's the same as writing
a = 2 && 8;
And 2 && 8
returns 8
, as 2 is truthy, so it's the same as writing a = 8
.
It's generally a bad idea to do variable assignment inside of an if
statement like that. However, in this particular case you're essentially doing this:
if(a = (2 && (b = 8)));
The (b = 8)
part returns 8
, so we can rewrite it as:
if(a = (2 && 8))
The &&
operator returns the value of the right hand side if the left hand side is considered true, so 2 && 8
returns 8
, so we can rewrite again as:
if(a = 8)
It is called operator precedence
(a=2 && (b=8))
In the above example. then results are evaluated against the main && sign.
(a=2 && (b=8)) evaluated to a = 2 && 8
So 2 && 8 return a = 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With