JavaScript let statement

Definition and usage

The let statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called "variable declaration":

let carName;

After declaration, the variable is empty (has no value).

To assign a value to a variable, use the equal sign:

carName = "Volvo";

You can also assign a value to a variable when declaring it:

let carName = "Volvo";

Tip:The value of a variable that has not been declared is undefined.

Example

Example 1

Create a variable named carName and assign "Volvo" to it:

let carName = "Volvo";

Try it yourself

Example 2

Use let to assign 5 to x and 6 to y, and display x + y:

let x = 5;
let y = 6;
document.getElementById("demo").innerHTML = x + y;

Try it yourself

Example 3

Declare many variables in one statement.

Start statements with let and separate variables with commas:

let lastName = "Gates",
age = 19,
job = "CEO";

Try it yourself

Example 4

Using let in loops:

let text = "";
for (let i = 0; i < 5; i++) {
  text += i + "
"; }

Try it yourself

Syntax

let name = value;

Parameter

Parameter Description
name

Required. The name of the variable.

The variable name must follow the following rules:

  • Must start with a letter, $, or _
  • Names are case-sensitive (y and Y are different)
  • Reserved JavaScript keywords cannot be used as names
value Optional. The value to be assigned to the variable.

Browser support

let is an ECMAScript6 (ES6) feature.

All modern browsers support ES6 (JavaScript 2015):

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Supported Supported Supported Supported Supported

Internet Explorer 11 and earlier versions do not support let.

Related pages

Reference Manual:JavaScript var Statement

Reference Manual:JavaScript const Statement

Tutorial:JavaScript Variable

Tutorial:JavaScript let

Tutorial:JavaScript Const

Tutorial:JavaScript Scope