Comma in an if statement
javascript
Solution
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.
EDIT
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
EDIT 2
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');
}
Problem
I've come 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 comparison (`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"; ... ```