JS: let Declaration

By Xah Lee. Date: . Last updated: .

New in ES2015.

“let” Syntax

let name; → declare a variable.

// declare variable
let x;
let y;

let name = expr; → declare a variable and assign it a value.

// declare variable and assign
let x = 4;

If a variable is not assigned, it has a value of undefined

let x;
console.log ( x === undefined ); // true

The following syntax are also supported:

// declare multiple variables
let a, b, c;
// 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 = 1; i <= 3; i++) {
    console.log(i);
}
// prints 1 to 3

// if you use “i” now, it is error because out of scope

// i // ReferenceError: i is not defined

Different between “let” and “var”

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

The scope of var is complex.

[see JS: var Name Scope]

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

var has a “name hoisting” feature, that is complex.

[see JS: var/function Declaration Order]

You should always use let or const, and never use var.

JS Variable Topic

  1. JS: Variable
  2. JS: let Declaration
  3. JS: const Declaration
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Global Variable
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon