Using the let Statement to Assign Variables

You want a variable’s life to be even shorter than the functional scope.

Use the let keyword when declaring and initializing variables in “block scope”. Block scope is delimited by curly braces {code here}. Each new set of curly braces defines a new block scope.


"use strict";

// aVariable is declared and assigned the string value Hello.
let aVariable = "Hello";
    // aSecondVariable is declared and assigned the string value Robot in block scope.
    let aSecondVariable = "Robot";
    // This prints Robot to the console.
if (aVariable === "Hello") {
    // A new variable named aVariable has been declared in this block.
    let aVariable = "Aloha";
    // Prints Aloha, not Hello, to the console due to the variable's scope.
// This statement causes a ReferenceError, because aSecondVariable is out of scope.
// This statement prints Hello.

The let keyword is an ECMAScript 6 (the new JavaScript standard) feature. Older browsers may not support its use.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s