본문 바로가기
programming/javascript

let

by hotdogya 2012. 12. 27.

in 연산자 찾다가 let도 발견

이것도 써본적이 없다.


let


변수의 블럭 스코프를 지정해 준다고 한다.


Block scoping

let declared variables are hoisted to the beginning of the enclosing block.

Redeclaration of the same variable in the same block scope raises a TypeError.

if (x) {
  let foo;
  let foo; // TypeError thrown.
}

However, function bodies do not have this limitation!

function do_something() {
  let foo;
  let foo; // This works fine.
}
Warning: ECMAScript 6 drafts (as of April, 2012) make this behavior illegal. That means that future versions of JavaScript will likely be consistent and raise a TypeError. if you do this, so you should avoid this practice!

You may encounter errors in switch statements because there is only one underlying block.

switch (x) {
  case 0:
    let foo;
    break;
    
  case 1:
    let foo; // TypeError for redeclaration.
    break;
}

Examples

A let expression limits the scope of the declared variable to only that expression.

var a = 5;
let(a = 6) alert(a); // 6
alert(a); // 5

Used inside a block, let limits the variable's scope to that block. Note the difference between var whose scope is inside the function where it is declared

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  console.log(a);  // 4
  console.log(b);  // 1
} 

console.log(a); // 5
console.log(b); // 1

You can use the let keyword to bind variables locally in the scope of loops instead of using a global variable (defined using var) for that.

for (let i = 0; i<10; i++) {
  alert(i); // 1, 2, 3, 4 ... 9
}

alert(i); // i is not defined

그냥 퍼웠다. 소스만 봐도 알수 있으니까~


자세한건 역시 원문을 보자

원문 : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/let


'programming > javascript' 카테고리의 다른 글

자바스크립트에서 함수는 변수 이다.  (0) 2013.02.05
extend, eval, load  (0) 2013.01.06
in  (0) 2012.12.27
Self-Executing Anonymous Functions (익명 함수)  (0) 2012.12.27
jQuery Selector, Filter  (0) 2012.12.26