Reputation: 126327
If I do:
var i = j = 0;
j
a local variable?Upvotes: 1
Views: 396
Reputation: 163238
Since the declaration of j
isn't in the same declaration expression as i
, the variable is either created in the outer scope or, if it exists there it will overwrite the value in the outer scope.
The reason why i
is now global is because of variable hoisting. You can break this down like this:
1) var i
2) j
, which now declares j
in the current scope, which is the containing scope since the expression is not bound to the current context because it's not using var
.
3) = 0
, which now assigns j
to 0
, and subsequently assigns j
to i
.
Proof?
Upvotes: 1
Reputation: 3084
check if it's on the window
object alert(window.j)
if it alerts it's value then it's global if not it's local (if it's not in a function when using the var
keyword then it's global and without var
then it's global no matter were you define it. so j and i are both global). example:
var i = j = 0;
function x(){
var r = 100;
alert(r);
}
alert(window.i); //will alert 0.
alert(window.j); //will alert 0.
x(); // will alert 100.
alert(window.r); //will alert undefined.
or you can use hasOwnProperty
like so alert(window.hasOwnProperty("i"))
which returns a boolean value.
by the way, trying to test this using jsfiddle will make i
return undefined
(might have something to do with the way jsfiddle protects it's own global namespace) so you'll need a blank html page to test this
Upvotes: 0
Reputation: 816404
For fun, here is another "proof":
(function() {"use strict"; var i = j = 0;}());
// throws "ReferenceError: assignment to undeclared variable j"
Upvotes: 2
Reputation: 1350
function test(a){
var i=j=0;
return i;
};
test(100);
alert(j);
alert(i);
Upvotes: 0
Reputation: 54378
(function(){
var i = j = 0;
})();
try{
alert(i);
}catch(e){
alert(e);
}
alert(j);
Not particularly proof...nor would I use an exception in a normal program flow unless it was indeed an exceptional case. But it does demonstrate the behavior.
Upvotes: 0
Reputation: 324630
After hoisting, your code looks like:
var i;
j = 0;
i = j;
Therefore i
is a local variable, but j
is not.
Upvotes: 6
Reputation: 16255
j
would be a global variable, or get assigned to a variable in an out scope:
(function() { var i = j = 0; })()
// i is undefined
// j is 0
var i = 42;
var j = 1;
(function() { var i = j = 0; })()
// i remains 42
// j is 0
Upvotes: 2