Hoisting
아래에 있는 선언을(만) 끌어올리는 것을 의미한다.
var 키워드에서 문제되는 현상
// 함수 선언 후 호출 -- 가능
function hello1() {
console.log('hello1');
}
hello1();
// 함수 호출 후 선언 -- 가능
hello2();
function hello2() {
console.log('hello2');
}
console.log(name); // undefined
name = 'Mark';
console.log(name); // Mark
var name = 'Gildong';
선언을 뒤에 하면 함수에 값을 할당해 준 상태임에도 불구하고 undefined로 출력되며 변수에 값을 할당해주자 함수값이 출력된다. 이는 hoisting이 선언만 불러오는 것임을 알 수있다.
하지만 const, let을 사용하면 var에서와 같은 문제가 발생하지 않는다.
const, let의 경우는 먼저 선언되어야 작동하기 때문에 hoisting 현상이 일어나지 않는다.