JavaScript: let and const Declarations (ES2015)

By Xah Lee. Date: . Last updated: .

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

let is similiar to var, except it has a scope of the nearest outer curly brackets {}.

const is similiar to let, except the value cannot be changed.

「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 the nearest enclosing curly brackets.

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

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); // ReferenceError: i is not defined
let x = 3;

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

console.log(x); // prints 3

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

〔➤see JavaScript: Variable/Function Declaration Order, Name Hoisting

「const」 Declaration

const is for declaring constants. It's similar to let, except you can't change its value once set.

// variable declared with const cannot be changed
const x = 3;
x = 4; // TypeError: Assignment to constant variable.

If a object value is declared const, you can still change properties of the object.

// if object is declared constant, the object properties can still be modified
const ob = {};
ob.p = 3;
console.log(ob); // { p: 3 }

const must have a value when declared.

// const must have a value
const x; // SyntaxError: Missing initializer in const declaration
x = 3;

ES2015 §ECMAScript Language: Statements and Declarations#sec-let-and-const-declarations

JavaScript Variable Topic

  1. JavaScript: Variable
  2. JavaScript: Variable/Function Declaration Order, Name Hoisting
  3. JavaScript Variable Scope: Function Level vs Block Level
  4. JavaScript: let and const Declarations (ES2015)
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.