I've e across a rather confusing statement in some JavaScript:
if (n = "value", a==b) {...
I take it that this assigns the value n
first and then performs a parison (a==b
) to determine whether to proceed with the if
statement. But why? Is there any advantage to doing this over say...
n = "value";
if (a==b) {...
or...
if (a==b) {n = "value"; ...
I've e across a rather confusing statement in some JavaScript:
if (n = "value", a==b) {...
I take it that this assigns the value n
first and then performs a parison (a==b
) to determine whether to proceed with the if
statement. But why? Is there any advantage to doing this over say...
n = "value";
if (a==b) {...
or...
if (a==b) {n = "value"; ...
n
is set in any case, in the third snippet n
will be set only if if
passes.
– Teemu
Commented
Feb 5, 2014 at 17:36
n
is restricted in anyway by delcaring it in the if
function (succinctly answered by Danilo below). In theory if n
was restricted to the scope of the if
statement then it could be available to the final parison, so even if the test fails n
gets its value for the scope of if
.
– user1945782
Commented
Feb 5, 2014 at 17:43
In JavaScript, whenever you put more than one expression inside a pair of brackets, they are evaluated as the last expression, like in the example below:
var a = (1, 2);
var b = a + 1; // b = 2 + 1 = 3
So, in your case, the interpreter executes the attribution n = "value"
and then parses the if taking a == b
as condition. It's the same as:
n = "value";
if (a == b) {
// ...
}
This article explains this behaviour.
However, this does not limit n
to the if
's scope. This same thing happens to var declarations in for
loops:
for (var i = 0; i < 10; i++) {
// Do stuff...
}
console.log(i); // Logs 10
As Ethan Brown mentioned, is also good to tell about variable hoisting, which is basically the fact that, in JavaScript, values can be assigned to variables before declaring them. The following code shows this behaviour and was extracted from this MDN article:
bla = 2
var bla;
// The above code is valid, since
// it's implicitly understood as:
var bla;
bla = 2;
The same occurs with functions:
foo();
function foo() {
console.log('bar');
}
Your assessment of the meaning is correct. There is no advantage other than pactness. Many would consider this poor practice, but it doesn't bother me.
Where it gets tricky is when you start calling functions that have side effects...then you can do some really weird stuff.
You're right - it's just a really confusing way to phrase assigning a variable and then running an if
statement. It's valid code, but equivalent to the less puzzling version, so this is most likely just a case of someone being too clever.