var
, let
, const
변수 키워드 모두 선언되면 변수 선언은 호이스팅
된다.
호이스팅
된다라는 의미는 변수가 선언된 스코프의 최상단으로 올라간다는 의미다.
var
의 경우에는 선언
과 undefined 초기화
가 호이스팅
된다.
console.log(x); // err: undefined
var x = 1;
x
를 출력해보면 자바스크립트 인터프리터가 x
의 존재를 인지했고 심지어 값!
까지 출력했다. 다만, 값이 undefined
. 이것이 가능한 이유는 var
키워드로 변수가 선언된 경우, 선언 뿐만 아니라 초기화까지 호이스팅되며 이때 호이스팅된 var x
의 값은 undefined
로 초기화된다.
이 2개의 키워드는 변수 선언만 호이스팅되며 초기화는 호이스팅되지않아서 var
변수와 다르게 선언된 변수에 초기화 이전에는 접근이 불가능하다.
// Reference Error!
// chrome, brave: 'x is not defined'
// firefox: can't access lexical declaration 'x' before initialization
console.log(x);
let x = 1; // declaration & initialization here
함수 선언식인 경우에 함수는 선언
, 초기화
모두 호이스팅된다.
// 리턴 값 100 출력
console.log(foo());
function foo() {
return 100;
}
함수 표현식인 경우에는 변수에 담기 때문에 변수 호이스팅 발생
// ReferenceError: can't access lexical declaration 'foo' before initialization
// 변수 let키워드이기에 선언만 호이스팅
console.log(foo());
let foo = function() {
return 100;
}
// undefined 출력
console.log(foo);
var foo = function() {
return 100;
}
// foo 호출시
// TypeError: foo is not a function
// foo는 undefined로 초기화된 상태인데 undefined에 함수 호출을 시도한 셈
console.log(foo());
var foo = function() {
return 100;
}