Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit to defining variables together with a comma vs separately in JavaScript?

Tags:

javascript

Reading Crockfords The Elements of JavaScript Style I notice he prefers defining variables like this:

var first='foo', second='bar', third='...';

What, if any benefit does that method provide over this:

var first='foo';
var second='bar';
var third='...';

Obviously the latter requires more typing but aside from aesthetics I'm wondering if there is a performance benefit gained by defining with the former style.

like image 573
Darrell Brogdon Avatar asked Jan 13 '10 17:01

Darrell Brogdon


People also ask

What are the ways to define variables in JavaScript What is the difference between them?

Basically we can declare variables in three different ways by using var, let and const keyword. Each keyword is used in some specific conditions. var: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and changeable also.

Can variables have commas?

Each variable is separated by a comma ( , ), and the last variable ends with a semicolon (;) which terminates the var statement.


1 Answers

Aside of aesthetics, and download footprint, another reason could be that the var statement is subject to hoisting. This means that regardless of where a variable is placed within a function, it is moved to the top of the scope in which it is defined.

E.g:

var outside_scope = "outside scope";
function f1() {
    alert(outside_scope) ;
    var outside_scope = "inside scope";
}
f1();

Gets interpreted into:

var outside_scope = "outside scope";
function f1() {
    var outside_scope; // is undefined
    alert(outside_scope) ;
    outside_scope = "inside scope";
}
f1();

Because of that, and the function-scope only that JavaScript has, is why Crockford recommends to declare all the variables at the top of the function in a single var statement, to resemble what will really happen when the code is actually executed.

like image 124
Christian C. Salvadó Avatar answered Nov 08 '22 18:11

Christian C. Salvadó