ma11hew28
ma11hew28

Reputation: 126327

JavaScript: How to determine a variable's scope?

If I do:

var i = j = 0;
  1. Is j a local variable?
  2. Prove it.

Upvotes: 1

Views: 396

Answers (7)

Jacob Relkin
Jacob Relkin

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?

enter image description here

Upvotes: 1

zero
zero

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

Felix Kling
Felix Kling

Reputation: 816404

For fun, here is another "proof":

(function() {"use strict"; var i = j = 0;}());
// throws "ReferenceError: assignment to undeclared variable j"

(Read more about strict mode)

Upvotes: 2

OQJF
OQJF

Reputation: 1350

function test(a){
    var i=j=0;
    return i;
};
test(100);
alert(j);
alert(i);

Upvotes: 0

Tim M.
Tim M.

Reputation: 54378

(function(){
    var i = j = 0;
})();

try{
    alert(i);   
}catch(e){
    alert(e);  
}

alert(j);

http://jsfiddle.net/kDGM3/1/

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

Niet the Dark Absol
Niet the Dark Absol

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

Faiz
Faiz

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

Related Questions