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.
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;
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)
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