Let and Const

let and const are new variable declaration mechanisms introduced in ES6. In this lesson, we will cover let, const and see how it leads to better code than the variables declared with var.

let

The following code is from ES5. Can you identify the problem here (specially look at line 1 and line 4).

Now Run the program to see the output. Did it match your expectation?

Console

It's confusing. var apples on line 4 was within a scope but it was able to influence the variable declared outside the scope. It's actually a feature called Hoisting where all variables declared in the function are moved to the top.

let is the new variable declaration mechanism that respects scopes and doesn't do Hoisting the way var does.

Look at the same code but now we've replaced var with let. Does it now match your expectation?

Console

Variables declared with var can be accessed before their declaration. Why? Because they are hoisted to the top so they are always available to every line of your function.

Look at the following weird looking code which is actually legit in Javascript.

Console

You cannot access variables before their declaration with let. Here's the same code but now you can see that it throws an error. Run the following code to see the error.

Console

Double declaration with let is also forbidden. Try it.

Every for here has it's own i variable, and no i is declared in global scope. It's another example where you can see that let doesn't hoist i to the top. Try it as well

Console

const

const disallows reassignment of variables. It's a static check. Run the code below.

There are may places in your code where you know that the value of the variable is set in stone and isn't going to change. It's a good idea to declare them with const.

Caveat: Many developers are confused about const objects or arrays. const protects you only against reassignment, but mutations are still allowed. Try running the following code.

Console