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

Difference between “let” and “var”

Tip: always use let. Never use var.

JS Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog