Just Chris


Bye Bye Var! Let and Const in ES6

JavaScript ES6 has a variety of functions to help the programmer code faster as well as in an efficient manner. Today let’s look at two particular functions, let and const.

The use of let and const is done as an alternative to the var function during the declaration of variables. Unlike var , let and const are block scoped. Another difference that let and const have when compared to var is the fact that while var gives a undefined error when accessed before declaring, let and const give a ReferenceError if they are accessed before declaration.

const does not allow reassignment

The error is due to TDZ, or Temporal Dead Zone. TDZ starts at the beginning of the block where let is declared and ends when let is encountered again in the user code.

TDZ is very useful as it helps to avoid bugs which appear when a variable is changed before its declaration is reached.

While let and const are similar, they are not exactly the same. The main difference between let and const is that const variables need to be declared using an initializer, or it will generate an error.

let will prevent mistakes of trying to redeclare an already declareed variable

Also declaration of the variable with the same name will throw an error. This helps to fix mistakes where one loses a reference when a variable is reassigned.

Let and Const are already replacing Var in many codebases, and are additional features of ES6 that will improve code.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

More by Just Chris

Topics of interest

More Related Stories