user2991761
user2991761

Reputation:

Scope chain - javascript

I am new to JavaScript, and while learning I got confused. Not sure about title of the question.

Coming straight to point -

var a = 4,
    say = console.log,
    globalA; // defined global variable's


doSome();
doSomeMore();

function doSome() {
    say(a);
    var a = 5;
    say(++a);
}

function doSomeMore() {
    say(a);
}

When I run it, this gives

undefined

6

4

Why is this when doSome executes it has value of a as undefined and not 4 ?

Upvotes: 0

Views: 35

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

What you're looking for is called hoisting.

It essentially means that when you declare var a in a function this gets moved to the top, and is equal to the following:

function doSome() {
    var a; //initialize the variable using hoisting
    say(a); //undefined
    a = 5;
    say(++a);
}

If you remove var in var a = 5 this works as you'd want it to as it then refers to the global a variable:

function doSome() {
    say(a); //4
    a = 5;
    say(++a);
}

Upvotes: 3

Murugan Pandian
Murugan Pandian

Reputation: 778

change your code

function doSome() {
    say(a);
    var a = 5;
    say(++a);
}

to

function doSome() {

var a = 5;
say(a);
say(++a);

}

Upvotes: 0

Related Questions