자바스크립트를 다루는 데에 있어서 아주 중요한 개념 중 하나인 Hoisting(호이스팅)에 대해서 다뤄보겠다.
함수, 변수 등의 선언을 위쪽으로 끌어올려 미리 선언하여 메모리 공간을 할당하는 것을 말한다.
함수의 선언문은 hoisting되기에 함수 선언을 코드의 맨 아래에 두어도 정상적으로 작동하는 모습을 볼 수 있다.
hello(); //hello!
function hello(){
console.log("hello!");
}
변수의 hoisting에서 유의해야 할 점이 몇 가지 있다.
var
키워드에서만 일어난다는 점이다. let
과 const
키워드에서는 hoisting이 발생하지 않는다.console.log(a); //undefined
var a = 'A';
console.log(a); //A
console.log(a); //ReferenceError: Cannot access 'a' before initialization
let a = 'A';
console.log(a); //ReferenceError: Cannot access 'a' before initialization
const a = 'A';