
인터프리터가 코드를 실행하기 전에 함수, 변수, 클래스, import의 선언문을 해당 범위의 맨 위로 끌어올리는 것처럼 보이는 현상
var, let, const, function, class)을 스코프에 등록let, const, class는 호이스팅이 일어나지 않는 것처럼 보이기도 함ReferenceError를 던지지 않고 값이 항상 undefined인 경우var는 2번,let, const, class 선언은 3번,import는 1, 4번으로 호출됨1. 함수 선언식
⭐ 전체 함수가 호이스팅 O
greet(); // "Hello, World!"
function greet() {
console.log("Hello, World!");
}
2. 함수 표현식
⭐ 변수만 호이스팅 되고, 함수 할당은 나중에 이루어짐!
sayHello(); // TypeError: sayHello is not a function
const sayHello = function() {
console.log("Hello, World!");
};
☑️ 변수 호이스팅 단계
선언 단계 (Declaration phase) : 변수를 실행 컨텍스트의 변수 객체에 등록초기화 단계 (Initialization phase) : 변수 객체에 등록된 변수를 위한 공간을 메모리에 확보할당 단계 (Assignment phase) : undefined로 초기화된 변수에 실제 값 할당1. var
⭐ 선언과 동시에
undefined로 초기화가 이루어짐
undefined로 '초기화'되어 메모리에 저장되기 때문에, ReferenceError가 발생하지 않는다!console.log(a); // undefined
var a = 10;
console.log(a); // 10
2. let
⭐ '선언'은 호이스팅되지만, TDZ로 인해 선언문 전에 접근 시
ReferenceError
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;
console.log(b); // 20
3. const
⭐ '선언'은 호이스팅되지만, TDZ로 인해 선언문 전에 접근 시
ReferenceError
console.log(c); // ReferenceError: Cannot access 'c' before initialization
const c = 30;
console.log(c); // 30
☑️ TDZ(Temporal Dead Zone)
⭐ 코드 실행 전에, 모듈이 로드됨
import문을 분석하고, 모든 종속 모듈을 평가함import문도 호이스팅이 된다)1. class 선언식
⭐ '선언'은 호이스팅이 되긴 하지만, '초기화'는 되지 않기 때문에 선언문 앞에서 사용할 수 없음
const personInstance = new Person("Alice"); // ReferenceError: Cannot access 'Person' before initialization
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
}
2. class 표현식
⭐ 변수만 호이스팅 되고, 클래스 할당은 나중에 이루어짐
const personInstance = new Person("Alice"); // ReferenceError: Cannot access 'Person' before initialization
const Person = class {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
};