Fadwa
Fadwa

Reputation: 1931

variables and function scope in javascript

I have this piece of code

var a = 5;
function woot(){
    console.log(a);
    var a = 6;
    function test(){ console.log(a);}
    test();
  };
woot();

i'm expecting 5 and 6 as an output, but i've got undefined and 6 instead.

Any thoughts?.

Upvotes: 0

Views: 400

Answers (3)

user1299518
user1299518

Reputation:

at the time of:

function woot(){
console.log(a);

..the a doesnt exist yet! if you want to use the outer a you need to call it like:

console.log( window.a );

Remove the a you have already in function and you can use, relaxed now, that console.log(a); which will refer to outer one (since there's no in your function anymore)

Otherwise, use console.log( window.a ); to differentiate the two alphas.

Upvotes: 0

James Allardice
James Allardice

Reputation: 166071

Variable declarations are hoisted to the top of the scope in which they appear. Your code is interpreted like this:

var a; // Outer scope, currently undefined
a = 5; // Outer scope, set to 5

function woot(){ // Function declaration, introduces a new scope
    var a; // Inner scope, currently undefined
    console.log(a); // Refers to inner scope 'a'
    a = 6; // Inner scope, set to 6
    function test(){ console.log(a);} // Refers to inner scope 'a' (now 6)
    test();
  };
woot();

When you declare a variable inside a function, that variable will shadow any variable with the same identifier that has been declared in an ancestor scope. In your example, you declare a in the global scope. You then declare another variable with the same identifier in the scope of the woot function. This variable shadows the a that you declared in the global scope.

Upvotes: 4

Bergi
Bergi

Reputation: 665545

The variable declaration (var keyword) is hoisted in the scope of your woot function, making it a local variable (shadowing the global variable a). It will be initialised as undefined, and return that value until you assign to it.

Upvotes: 0

Related Questions