JS: let Declaration

By Xah Lee. Date: . Last updated: .

New in JS2015.

Syntax

let name;

declare a variable.

// If a variable is not assigned, it has a value of undefined
let x;
console.log(x === undefined);
let name1, name2, etc;

declare multiple variables.

// declare multiple variables
let a, b, c;
let name = val;

declare and assign.

// declare and assign
let x = 4;
let name_or_assign_1, name_or_assign_2, etc;

declare or assign multiple variables

// declare 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
}

if there is no outer curly brackets, scope is global.

// global variable with let
let x = 5;
console.log( x === 5)

// unlike var, the variable does not become a property of global object
console.log( window.x === undefined)

“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” here, it is error because out of scope

Difference between “let” and “var”

💡 TIP: always use let. Never use var.

JavaScript, variable