let

Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Parameters
  4. 4. Description
  5. 5. Examples
  6. 6. See also
Table of contents
  1. 1. Summary
  2. 2. Syntax
  3. 3. Parameters
  4. 4. Description
  5. 5. Examples
  6. 6. See also

Non-standard

Introduced in JavaScript 1.7

Summary

Declares a local variable, optionally initializing it to a value.

Syntax

let definition:

let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];

let expression:

let (var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]]) expression;

let statement:

let (var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]]) statement;

Parameters

Parameter Description
var1, var2, …, varN Variable name. It can be any legal identifier.
value1, value2, …, valueN Initial value of the variable. It can be any legal expression.
expression Any legal expression.
statement Any legal statement.

Description

let allows you to declare variables, limiting its scope to the block, statement, or expression on which is used. This is unlike the var keyword, which defines a variable globally, or local to an entire function regardless of block scope.

Examples

A let expression limit the scope of the variable declared only in that expression.

var a = 5;
let(a = 6) alert(a); // 6
alert(a); // 5

 Used inside a block, let limits the variable's scope to that block. Note the difference between var which its scope is inside the function where is declared

var a = 5;
var b = 10;
if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  console.log(a);  // 4
  console.log(b);  // 1
} 
console.log(a); // 5
console.log(b); // 1

You can use the let keyword to bind variables locally in the scope of for loops instead of using a global variable (defined using var) for that.

for (let i = 0; i<10; i++) {
  alert(i); // 1, 2, 3, 4 ... 9
}

alert(i); // i is not defined

Tags (0)

Edit tags
  • No tags

Attachments (0)

 

Attach file