Comma in if statement

In some kind of JavaScript, I came across a rather confusing statement:

if (n = "value", a==b) {... 

I believe that it first assigns the value n , and then performs a comparison ( a==b ) to determine if should be executed. But why? Are there any advantages to this, tell me ...

 n = "value"; if (a==b) {... 

or...

 if (a==b) {n = "value"; ... 
+6
source share
3 answers

In JavaScript, when you put multiple pairs inside a pair of brackets, they are evaluated as the last expression, as in the example below:

 var a = (1, 2); var b = a + 1; // b = 2 + 1 = 3 

So, in your case, the interpreter performs the attribution n = "value" , and then analyzes if it accepts the condition a == b as a condition. This is the same as:

 n = "value"; if (a == b) { // ... } 

This article explains this behavior.

EDIT

However, this does not limit n the if region. The same thing happens with var declarations in for loops:

 for (var i = 0; i < 10; i++) { // Do stuff... } console.log(i); // Logs 10 

EDIT 2

As Ethan Brown mentioned, it’s also useful to talk about variable lifting, which basically means that in JavaScript values ​​can be assigned to variables before they are declared. The following code shows this behavior and was extracted from this MDN article :

 bla = 2 var bla; // The above code is valid, since // it implicitly understood as: var bla; bla = 2; 

The same thing happens with functions:

 foo(); function foo() { console.log('bar'); } 
+3
source

Your estimate of the value is correct. There is no advantage besides compactness. Many people consider this bad practice, but it does not bother me.

Where it becomes difficult when you start calling functions that have side effects ... then you can do some really weird things.

+3
source

You are right - this is just a confusing way of phrases that assign a variable and then run the if . This is valid code, but it is equivalent to a less mysterious version, so this is most likely just a case where someone is too smart.

+1
source

All Articles