webbyweb
webbyweb

Reputation: 435

Javascript Function Scope Confusion

Can someone explain this to me:

var test = 5;

// prints 5;
function printMe1(){
    console.log(test);
}

// prints "undefined"
function printMe2(){
    console.log(test);
    var test = 10;
}

Is this because printMe2 creates a local variable of "test"? And if so, why does the log statement refer to the local variable, if it is declared after it?

And also, if JS is an interpreted language, shouldn't the code be interpreted line by line? In which case the log statement shouldn't be able to know that the local "test" variable is declared later?

Upvotes: 1

Views: 92

Answers (2)

anuj agarwal
anuj agarwal

Reputation: 11

there is a concept in javascript "hoisting" so in hoisting variables and function declarations are moved to the top of their scope before code execution. remember only declaration, not the definition. that's why in your code var test is showing undefined because you are using this variable before defining it.

var test;
function printme2(){
console.log(test)
test=10
}
printme2()

Upvotes: 1

webbyweb
webbyweb

Reputation: 435

I just did some googling and found the answer.

It is because Javascript "hoists" variable declarations to the top of the scope. So the local "test" variable was declared at the top of the function scope, thus the reason why printing it gave "undefined".

(if any of this wrong let me know please :) )

Upvotes: 0

Related Questions