If you are new to JavaScript and struggling to understand the concepts of scope and hoisting, you are not abnormal. I remember how long it took me to get a firm grasp on these two tricky concepts. In this blog, we'll take a look at a simple example to help clear things up.
Check out this little write up on scope in JavaScript for a bit more on scope ๐
What will the browser's console show if the following code gets executed?
var text = 'outside';
function logIt(){
console.log(text);
var text = 'inside';
};
logIt();
Stop. Don't scroll down and don't copy this into the DevTools Console, yet. Take a minute to look closely at the code and think about it.
Solution
The console will log undefined. To understand this, let's look at hoisting and scope in JavaScript.
Function-level scope
Functions create new scopes in JavaScript:
function setVar(){
// inside this function we have a new scope
// so this variable, declared in this function's scope, won't be available outside the function
var varInFunction = 'inside a function';
}
setVar();
console.log(varInFunction); // throws 'ReferenceError: varInFunction is not defined'
Blocks like if statements and for loops do not create a new scope:
if (true) {
// this if statement doesn't create a new scope
// so varInIf is available in the global scope
var block = 'inside an if statement';
}
console.log(block); // logs 'inside an if statement'
Declaration vs. assignment
A variable declaration simply tells the interpreter that a variable exists. By default it initializes the variable to undefined:
var dog;
console.log(dog); // logs undefined (NOT a ReferenceError)
A variable assignment assigns a value to the variable:
dog = "Lino";
We can both declare and assign in the same line:
var dog = "Lino";
Hoisting
In Javascript, variable declarations are "hoisted" to the top of the current scope. Variable assignments, however, are not.
Returning to the original problem:
var text = 'outside';
function logIt(){
console.log(text);
var text = 'inside';
};
logIt();
The declaration (but not the assignment) of text gets hoisted to the top of logIt()
. So our code gets interpreted as though it were:
var text = 'outside';
function logIt(){
var text;
console.log(text);
text = 'inside';
};
logIt();
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.
Recap
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 function or the top of the script if the variable isn't in a function.
Next step
Try looking into the differences when using "let" and "const" instead of "var" to declare variables in JavaScript. Also, what is a lexical environment and what does it have to do with the concepts covered in this blog?
Happy coding!
Top comments (0)