JS: let Declaration

By Xah Lee. Date: . Last updated: .

New in ES2015.

Now you can have block-level variables, using let.

let has the same syntax as var, but let has a scope of the nearest outer curly brackets {}.

“let” Syntax

Use let name; to declare a variable.

// declare variable
let x;
let y;
// declare multiple variables
let a, b, c;
// declare variable and assign
let x = 4;
// declare variable and assign multiple variables
let a = 1, b = 2, c = 3;
// declare multiple variables, some with value
let a, b = 2, c;

console.log(a); // undefined
console.log(b); // 2
console.log(c); // undefined

“let” Scope

The scope of let is the nearest enclosing curly brackets.

// using let inside curly brackets
{
    let x = 3;
    {
        let x = 4;
        console.log(x); // 4
    }
    console.log(x); // 3
}

“let” with “For Loop”

When used with “for loop”, the scope of “let” is the whole “for” statement.

// using “let” with for loop
for (let i = 0; i < 4; i++) {
    console.log(i);
}

console.log(i); // ReferenceError: i is not defined
let x = 3;

if ( true ) {
    let x = 4; // block level var
};

console.log(x); // prints 3

No Name Hoisting

The let doesn't have name hoisting as var does. That means, you can't use the variable before its let declaration.

〔►see JS: var/function Order

JavaScript Variable Topic

  1. JS: Variable
  2. JS: var/function Order
  3. JS: var Name Scope
  4. JS: let Declaration
  5. JS: const Declaration
Like what you read? Buy JavaScript in Depth