Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of multiple vars defined on the same line?

Tags:

javascript

Simple question. Today I was writing something simple like this:

var deferred = null;
var user = null;
var campaigns = null;

But my editor suggested me to put the definition of these vars on the same line, like this:

var deferred = user = campaigns = null;

The scope of the two definitions is the same?

I was wondering if with the same-line-definition make user and campaigns global and not local to the function where them have been defined.

like image 689
Cla Avatar asked Dec 25 '22 14:12

Cla


2 Answers

Warning... you are not declaring three variables. You are only declaring one (deferred). This will mean the others leak to the global scope (or throw a reference error in strict mode).

You need to declare all three variables first:

var deferred, user, campaigns;
deferred = user = campaigns = null;

To demonstrate it, run this in your console:

(function () {
    "use strict";
    var x = y = null; // Throws a reference error
}());

In my opinon the cleanest solution is to use a single var statement with multiple initialisers (or simply forget the initialisers... do you really need to initialse everything to null? They'll be implicitly initialised to undefined anyway):

var deferred = null,
    campaigns = null,
    user = null;
like image 127
James Allardice Avatar answered Dec 28 '22 05:12

James Allardice


To complement the other answers, javascript has what is known as function scope, no matter in what part of the function you declare the variable, it will be moved to the begining of the function. For example:

function test() { 
    var i;

    i = 5;
    console.log(i);
    // Some more code code 

    for (var j = 0; j < i; j++) {
        var k = i + j;
        console.log(k);
    }
}

Will be interpreted by the javascript engine as this:

function test() { 
    var i;
    var j;
    var k;        

    i = 5;
    console.log(i);
    // Some more code code 

    for (j = 0; j < i; j++) {
        k = i + j;
        console.log(j);
    }
}

(As poited by @Alex K, this process is known as hoisting).

There is no such thing as block scope in javascript, and moving your variables to the start of the function is one the jslint recomendations will yell at you.

So, declarations like:

var i, j;

Or

var i;
var j;

Or even,

var i = 0, j = 3;

Use the same scope, function scope.

For more deep info about some javascript gotchas, consult the Douglas Crockford's javascript material (videos, site, etc)

like image 23
higuaro Avatar answered Dec 28 '22 07:12

higuaro