JavaScript
호이스팅 - JavaScript
기린성준
2024. 2. 25. 19:59
호이스팅이란?
인터프리터가 코드를 실행하기 전에 함수, 변수, 클래스 또는 임포트(import)의 선언문을 해당 범위의 맨 위로 끌어올리는 것처럼 보이는 현상이다.
호이스팅은 선언문을 위로 올리고 할당은 호이스팅 하지 않는다.
예시
- var (불가능)
console.log(a); // undefined
var a = 1;
- let (불가능)
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a =1;
- const (불가능)
console.log(a); // ReferenceError: Cannot access 'a' before initialization
const a =1;
여기서 var는 undefined가 나오고 let, const는 에러가 나온다.
그래서 let, const는 호이스팅이 안되는 거냐? 라고 하면 아니다 오류 메세지를 읽어보면
선언은 되있지만 초기화 전에는 접근이 불가능하다고 나온다.
- 함수 선언식 (가능)
a(); // Hello
function a(){
console.log("Hello");
}
- 함수 표현식 (불가능)
a(); // ReferenceError: Cannot access 'a' before initialization
const a =() =>{
console.log("Hello");
}
- 클래스 선언식 (불가능)
let a = new A("a"); // ReferenceError: Cannot access 'A' before initialization
class A{
constructor(a){
this.a = a;
}
}
- 클래스 표현식 (불가능)
let a = new A("a"); // ReferenceError: Cannot access 'A' before initialization
console.log(a);
let A = class{
constructor(a){
this.a = a;
}
}
- import 문
let head = new Node(null); // ReferenceError: Cannot access 'Node' before initialization
head.next = new Node(1);
print(head);
const {Node, print} = require("./codingTest/node");
결론
함수 선언식만 선언보다 사용을 먼저 해도 사용이 가능하다.
대부분은 먼저 선언과 할당 후에 사용해야 오류가 나지 않는다.
선언과 할당을 먼저 하고 그다음에 사용하도록 해야겠다.