hoisting이란?

2019-07-02

hoisting이란 자바스크립트의 기본동작 중 하나이다.
사전적 정의로는 끌어올리다라는 뜻이다.

1
2
3
console.log(a); // undefined
let a = 10;
console.log(a); // 10

첫번째 콘솔에서 a가 undefined가 나온 이유는 자바스크립트 엔진 구동시 선언문을 가장 최우선으로 헤석한다.
호이스팅 개념으로 작성하면 아래와 같다.

1
2
3
4
let a;
console.log(a); // undefined
a = 10;
console.log(a); // 10

변수가 함수 내에서 정의되면 선언이 함수의 최상위
변수가 함수 밖에서 정의되면 선언이 전역 컨텍스트의 최상위

아래의 코드와 같다.

1
2
3
4
5
6
7
let a = 10;

function A () {
console.log(a); // undefined
let a = 12;
console.log(a); //12
}

함수 선언문은 호이스팅이 되지만 함수 표현식은 호이스팅이 되지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
console.log(typeof funcA); //function
console.log(typeof funcB); //undefined

funcA(); // a
funcB(); // 스크립트 에러 발생

function funcA() {
console.log('a)
}
const funcB = function() {
console.log(b)
}

funcA는 함수선언문이기 때문에 호이스팅이 되어 위와 같이 출력된다.
그러나 funcB는 타입을 체크하는 콘솔에는 funcB의 변수르 선언한것이므로 undefined가 찍히고
함수를 실행을 하면 funcB is not a function이라는 에러가 발생한다.
호이스팅 개념으로 작성하면 아래와 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function funcA() {
console.log('a)
}
const funcB;
console.log(typeof funcA); //function
console.log(typeof funcB); //undefined

funcA(); // a
funcB(); // 스크립트 에러 발생


funcB = function() {
console.log(b)
}