The let Statement


The let statement declares a block scope local variable, optionally initializing it to a value.

Description

let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to value only when parser evaluates it (see below).

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

Syntax


/**
 * Paramaters
 * 
 * var1, var2, …, varN - The names of the variable or variables to declare. Each must be a legal JavaScript identifier.
 * 
 * value1, value2, …, valueN Optional - For each variable declared, you may optionally specify its initial value to any legal JavaScript expression.
 * 
 */

let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN];
1
2
3
4
5
6
7
8
9

Rules


At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

Code


Examples


Scoping Outcome Example

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1
1
2
3
4
5
6
7
8
9
10
11

Let Scope Example Two

let name = 'Frodo';

if (true) {
  let name = 'Sam';
  console.log(name)
}

console.log(name)
1
2
3
4
5
6
7

Playground Examples


Resources

MDM Let

Last Updated: 8/11/2019, 10:51:29 PM