0

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 ?

4

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this makes real sense. Even when I was using window.a I was getting my value. Thanks :) Accepting (in 3 min) & Up-voted (esp. for the link)
0

change your code

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

to

function doSome() {

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.