What is hoisting in JavaScript?
Show answer — try answering out loud first
Hoisting is the behavior by which variable and function declarations are conceptually "moved" to the top of their scope before the code runs. Function declarations and var undergo hoisting, but var is initialized to undefined, while let and const remain in the Temporal Dead Zone.
Before running your code, JavaScript "registers" the declarations. This creates the illusion that it moves them to the top.
function nombre() {}: undergoes full hoisting. You can call it before writing it.var x: the declaration is hoisted, but not the assignment. That is why it holdsundefineduntil the line that gives it a value runs.letandconst: are also registered, but you cannot use them before declaring them. They are in the Temporal Dead Zone and throw an error.
// Function declarations: they can be used beforehand
saludar(); // "Hola" — works
function saludar() {
console.log("Hola");
}
// var: the declaration is hoisted, not the value
console.log(x); // undefined (no error, but not 5 yet)
var x = 5;
console.log(x); // 5
// let/const: error if used beforehand (Temporal Dead Zone)
// console.log(y); // ReferenceError
let y = 10;
// A function expression with var does NOT behave like a declaration
// miFuncion(); // TypeError: miFuncion is not a function
var miFuncion = function () {
console.log("expresión");
};
Believing that "hoisting physically moves the code to the top". It moves nothing: JavaScript only registers the declarations in memory before running. Another mistake is thinking that function expressions (var f = function(){}) behave like function declarations: they do not; only the var variable is hoisted (as undefined).
"Hoisting is when JavaScript registers the declarations before running the code, giving the impression that it raises them to the top. Function declarations undergo full hoisting, so I can call them before writing them. With
var, the declaration is hoisted but not the value, which is why it holdsundefinedif I use it beforehand. Withletandconst, if I use them before declaring them, I get an error because of the Temporal Dead Zone."
What does this print?
console.log(a);
console.log(b);
var a = 1;
function b() {}
See answer
It prints undefined and then [Function: b]. The var a declaration is hoisted but not its value (hence the undefined). The function b undergoes full hoisting, so it already exists.