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"; ...
Use a comma if the if clause is at the beginning of the sentence. Example: If I go to London, I will visit the Tower. Don't use a comma if the if clause is at the end of the sentence. Example: I will visit the Tower if I go to London.
a. Common starter words for introductory clauses that should be followed by a comma include after, although, as, because, if, since, when, while.
If turmeric will ease my arthritis pain, I will take some every day. Note that the action in the if clause hasn't happened yet, but will happen after the action in the main clause is taken.
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');
}
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