Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma in an if statement

Tags:

javascript

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"; ...
like image 521
Paul Avatar asked Feb 05 '14 17:02

Paul


People also ask

Where does the comma go when using IF?

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.

Do you put a comma before or after if?

a. Common starter words for introductory clauses that should be followed by a comma include after, although, as, because, if, since, when, while.

How do you use if/then in a sentence?

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.


1 Answers

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');
}
like image 166
Danilo Valente Avatar answered Sep 24 '22 23:09

Danilo Valente