Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment inside an 'if' condition in JavaScript

How does the below code execute?

if(a=2 && (b=8))
{
    console.log(a)
}

OUTPUT

a=8
like image 780
Jay Shukla Avatar asked Apr 08 '14 12:04

Jay Shukla


People also ask

Can you put a variable in an if statement JavaScript?

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.

Can we assign value to variable in IF statement?

Yes, you can assign the value of variable inside if.

Can we use assignment operator in if condition?

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)

How do you set a variable based on a condition?

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


3 Answers

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.

like image 99
adeneo Avatar answered Oct 13 '22 14:10

adeneo


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)
like image 19
Anthony Grist Avatar answered Oct 13 '22 15:10

Anthony Grist


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

like image 8
Jaykumar Patel Avatar answered Oct 13 '22 14:10

Jaykumar Patel