JavaScript: let Declaration

By Xah Lee. Date: . Last updated: .

New in JS2015.

Syntax

let name;
declare a variable.
let name1, name2, name3 etc;
declare multiple variables.
let name = val;
declare and assign.
let name1 = val1, name2 = val2, name3 = val3 etc;
declare and assign multiple variables
let name_or_assign_1, name_or_assign_2 etc;
declare variables, some with assignment.
let x; // declare
let y = 4; // declare and assign

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

Difference between “let” and “var”

Tip: always use let. Never use var.

JavaScript variable

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc