아래 이미지에서 Identifier이 변수
var myNumber = 23;
var newVar = 24;
//이렇게 변수를 선언했을 때 아래 그림과 같이 JS엔진에서 처리된다.
만약 원시(Primitive) 타입이 아닌 객체를 변수에 할당했을 때는 아래 그림과 같다
var newVar = 23;
var myNumber = 24;
var myString = 'abcd';
var myArray = [];
let a; //선언,초기화
a=1; //할당
let b = 1; //선언, 초기화, 할당 한번에
//호이스팅과 TDZ는 나중에 호이스팅에서 자세히 다루도록하자
ES6(ECMAScript2015) 등장 이전에는 많은 문제가 있음에도 var로 변수를 선언해왔다.
Scope of var
scope는 기본적으로 변수를 사용할 수 있는 범위.
함수 레벨 스코프로 함수 내부에 선언된 변수만 지역변수로 한정하고 나머지는 모두 전역변수가 된다.
function func() {
if (true) {
var a = 5;
console.log(a); // 5
}
console.log(a); // 5
}
func(); // 5
console.log(a); // ReferenceError: a is not defined
if(true){
var b = 10; //함수가 아닌 if에서는 전역 변수가 됨.
}
console.log(b); //10
hihi는 func 함수 밖에서 사용할 수 없다.
var hello = 'hello';
var hello = 'world';// 재선언 문제 없음
hello = 'every'; //업데이트도 문제없음
console.log(hello);
var hello = 'hello';
//라고 쓰고 실행하면
//실행 할 때는 내부적으로 아래와 같이 됨
var hello; //상위로 올라옴 호이스팅, 실제로 코드가 이동하는건 아니고 미리 선언하고 초기화 해둠
console.log(hello); // undefined
hello = 'hello';
이러한 문제때문에 var는 많은 부작용을 초래할 수 있었고 let, const가 등장
블록 레벨 스코프
//let과 const의 블록{} 레벨 스코프
function func(){
if(true){
const hello = "hello";
console.log(hello); // "hello"
}
console.log(hello); ReferenceError: hello is not defined
}
console.log(hello); ReferenceError: hello is not defined
예시 코드에서는 if문을 블록의 예로 들었지만 for, while, try/catch 등 모든 블록{} 에서 유효한다.
업데이트 가능하지만 재선언 불가
블록 레벨 스코프
업데이트, 재선언 모두 불가
호이스팅은 별도 글에서 다시 정리