자바 스크립트의 variable declare 은 run-time 이전 단계에서 먼저 실행된다. 이처럼 변수 선언문이 코드의 선두로 끌어 올려진 것 처럼 동작하는 자바 스크립트의 고유의 특징을 variable hoisting(declare + initialize) 이라고 한다.
ES5 까지 사용되어온 var 키워드는 아래와 같은 문제점이 있다.
(function() {
var shit = "fuck";
if (true){
var shit = "yo"; // Allow duplicate declaration
}
console.log(shit); // Function level scope result: yo
})();
// Variable hoisting
console.log(shit); // undefined
shit = "yo";
console.log(shit); // yo
var shit;
Allow duplicate declaration 과 function level scope 문제는 위 코드 예제로 알 수 있다. variable hoisting 에 의해 끌어올려진 변수는 코드 흐름상 맞지 않고 가독성을 떨어뜨리며 오류를 발생시킬 여지를 남긴다.
ES6 부터 기존 var 키워드의 문제점을 보완한 let 과 const 가 추가되었다.
const 는 let 과 대부분 동일 하므로 let 과 다른점을 기술한다.