[JavaScript – ES2015] – let, const

In JavaScript, the global variable is pure evil. To overcome this, you have been used “var” to define local variable. But the scope of “var” has been confusing developers so long. Now with “let” and “const”, we can create a real block-scope variables.

 

1. Let

We have been used in “var” to declare the variables. The scope of “var” is function-wide. Let’s look at the following example.

function foo() {
    {
        var a = 10;
    }
    console.log('a = ' + a);
}
foo(); // a= 10

The variable ‘a’ is still accessible outside of the defined block. It can be accessed anywhere in the function because it is hoisted to the top of the function.

let” creates the block-scope variables.

function foo() {
    {
        let a = 10;
    }
    console.log('a = ' + a);
}
foo(); // SCRIPT5009: 'a' is not defined

It is an error to use the let variable outside the block.

 

2. Const

The “const” is another construct to define block-scope variable. The value should be assigned in a single line.

function foo() {
    {
        const c = 10;
        c = 20;
    }
}
foo(); //  SCRIPT1055: Assignment to const

Any assignment after the initialization causes an error.

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 )

Connecting to %s