Hoisting Flashcards
What is hoisting?
The hoisting of functions and variables is the reason why we can use some of them before they are actually declared.
test();
function test() {
console.log(“working”);
}
The code above will log the string “working” even though the function is called before it’s declared.
The common explanation that is given for this behaviour is that function and variable declarations are pulled to the top of their scope. So when you try to access them, they have already been declared. So the above example becomes:
function test() {
console.log(“working”);
}
test();
Variables are also hoisted but in a different way. Only the declaration of the variable is “pulled” to the top. The value assignment will stay where it is. In other words, we can’t access the value of a variable in the same way that we can call functions.
How does hoisting work with function expressions?
We need to be careful with function expressions…
console.log(test); //undefined
console.log(test()); // TypeError: test is not a function
var test = function() {
console.log(“test”);
}
Again, only the declaration is pulled to the top while the actual assignment of the function as a value will stay where it is. So when we try to call “test” as a function, we will get an error.
In ES6, are let and const hoisted?
Variables created with let and const are not hoisted. This means that the definition is not pulled to the top as it is for var.