BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE JS Interview Notes - Variables const, let, var and Hoisting

Understanding variable declaration methods and internal mechanisms in JavaScript execution.

影片縮圖

Lazy to read articles? Then watch videos!

Why use const / let / var?

KeywordReassignableRedeclarableScopeUsage
varFunction ScopeNot Recommended
letBlock ScopeMutable Data
constBlock ScopeConstants, Function Definitions

Hoisting Principle and TDZ (Temporal Dead Zone)

JavaScript hoists variable and function declarations to the top of their scope before execution.

var declarations are hoisted and initialized to undefined

let and const are hoisted but not initialized, entering TDZ

TDZ (Temporal Dead Zone) is the period when variables cannot be accessed

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError
let b = 10;

console.log(c); // ReferenceError
const c = 10;

function declaration vs const function expression

Only function declarations are fully hoisted; const function expressions are not hoisted.

TypeHoistedCallable Before Declaration
function declaration
const function expression
foo(); // 正常執行
function foo() {
  console.log("function declaration");
}

bar(); // ReferenceError
const bar = function () {
  console.log("function expression");
};

🔥 Common Interview Questions

(1) Explain Hoisting

Answer: Hoisting is when JavaScript moves variable and function declarations to the top before execution, like this:

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError
let b = 10;

console.log(c); // ReferenceError
const c = 10;

So, var declarations are hoisted and initialized to undefined, while let and const are also 'hoisted' but enter the TDZ (Temporal Dead Zone) without initialization, resulting in a ReferenceError.

(2) Which of the following will execute successfully? Why?

foo();
function foo() {
  console.log('foo');
}

bar();
const bar = function () {
  console.log('bar');
};

Answer: foo is a function declaration, which is hoisted and can be used before declaration; bar is a const function expression, which is not hoisted and will throw a ReferenceError.

(3) Will this code error? Why?

const person = { name: 'Alice' };
person.name = 'Bob';

Answer: No error. const only prevents reassignment of the variable binding, but object properties can still be modified.