티스토리 뷰
https://leanpub.com/understandinges6/read#leanpub-auto-block-bindings 을 정리한 내용입니다.
자바스크립트에는 두 가지 scope가 존재한다.
- Local scope : 함수 범위
- Global scope : 전역 범위
var로 변수를 선언하면, 해당 scope의 맨 위에서 선언한 것처럼 처리된다. (hoisting)
function myFunc(condition) { if (condition) { console.log(a); // undefined } else { var a = 1; console.log(a); // 1 } console.log(a); // undefined }
실제로는 아래와 같다.
function myFunc(condition) { var a; if (condition) { console.log(a); // undefined } else { a = 1; console.log(a); // 1 } console.log(a); // undefined }
ECMAScript 2015에는 block scope가 추가되었다.
let으로 선언한 변수는 해당하는 블록에서만 유효하고, 재선언이 불가능하다.
const로 선언한 변수도 동일하다.
단, const로 선언할 때에는 선언과 동시에 값을 초기화해야하고, 값의 binding을 변경할 수 없다.
const list = []; list.push('a'); console.log(list); // ['a']for loop에서 const를 사용할 때, 다음 예제는 에러가 발생한다.
const list = ['a', 'b', 'c']; for (const i = 0; i < list.length; i++) { // TypeError: Assignment to constant variable. console.log(list[i]); }for-of 또는 for-in 을 사용하면 매번 새로운 바인딩이 생성되기 때문에 에러가 발생하지 않는다.
const list = ['a', 'b', 'c']; for (const item of list) { console.log(item); }
'Javascript > Understanding ECMAScript 6' 카테고리의 다른 글
Strings and Regular Expressions (0) | 2018.12.25 |
---|
댓글