1

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?

5
  • 1
    variable hoisting. Commented Jun 17, 2018 at 20:34
  • 1
    JS is not interpreted line by line. The “interpreted” distinction beyond that isn’t very important. When it comes to scope, it doesn’t matter where a variable is declared; if it’s declared somewhere in that scope, it’s the target of its name in its scope. Use let and const, never var, to get proper errors about this. Commented Jun 17, 2018 at 20:35
  • There are already tons of answers here and online about scoping in JS. Also search for "hoisting" Commented Jun 17, 2018 at 20:37
  • @Jonathan i found a LOT of answers but not one canonical one for a duplicate flag. Sure, i could just flag it as duplicate for any of the hundreds of questions about this, but am searching for a "big protected post" explaining this and didn't find any yet. Commented Jun 17, 2018 at 20:39
  • "if JS is an interpreted language, shouldn't the code be interpreted line by line?" - nope, that's not what "interpreted" means at all Commented Jun 17, 2018 at 20:49

2 Answers 2

1

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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 :) )

1 Comment

Glad you found the answer in your own-although maybe try that first next time ;)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.