Using the let Statement to Assign Variables

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

Solution
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.

Examples

"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.
    console.log(aSecondVariable);
}
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.
    console.log(aVariable);
}
// This statement causes a ReferenceError, because aSecondVariable is out of scope.
console.log(aSecondVariable);
// This statement prints Hello.
console.log(aVariable);

Comments
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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s