function test() { console.log(x); var x = 5; console.log(x); } test();
The variable x is hoisted to the top of the function with an initial value of undefined. So the first console.log(x) prints undefined. Then x is assigned 5, so the second console.log(x) prints 5.
console.log(a); let a = 10;
The variable a is hoisted but is in a temporal dead zone until its declaration is reached. Accessing it before initialization causes a ReferenceError.
console.log(foo); var foo = 1; function foo() {} console.log(foo);
The function foo is hoisted first, so the first console.log(foo) prints the function. Then the var foo = 1 assignment overwrites foo with 1, so the second console.log(foo) prints 1.
console.log(bar); const bar = 3;
Like let, const variables are hoisted but not initialized. Accessing them before declaration causes a ReferenceError.
console.log(x);
var x = 7;
Why does it print
undefined instead of throwing an error?Variables declared with var are hoisted to the top of their scope and initialized with undefined. So when console.log(x) runs, x exists but has the value undefined.