If we execute this Javascript, what will the browser's console show?
It's not "outside".
It's not "inside".
The script won't throw an error!
The console will log undefined.
To understand this, we need to explain a few things about Javascript.
Method-level scope. Methods create new scopes in Javascript:
Blocks like if statements and for loops do not create a new scope (this is also true of Python and recent versions of Ruby, but untrue of Java and C):
Declaration vs. assignment. A variable declaration simply tells the interpreter that a variable exists. By default it initializes the variable to undefined:
A variable assignment assigns a value to the variable:
We can both declare and assign in the same line:
Hoisting. In Javascript, variable declarations are "hoisted" to the top of the current scope. Variable assignments, however, are not.
So returning to the original problem:
The declaration (but not the assignment) of text gets hoisted to the top of logIt. So our code gets interpreted as though it were:
So we have a new variable text inside of logIt that is initialized to undefined, which is what it holds when we hit our log statement.
Remember: when you declare a variable in JavaScript (using "var"), that variable declaration is "hoisted" to the top of the current scope—meaning the top of the current method or the top of the script if the variable isn't in a method.
Hoisting can cause unexpected behavior, so a good way to keep things clear is to always declare your variables at the top of the scope.