ES6 Basics Part 1 – const and let

ES6 can be thought of as a new version of Javascript. Currently, most JS is ES5.

Over the next few articles, I’m going to break down the new features & syntax of ES6 into bite-size chunks. Please note that some experience writing JS is required to make full uses of these articles.

This is part 1 of many so please keep checking back for the next article in the series.
Part 2 – Template Strings can be found here.
Part 3 – Arrow Functions can be found here.
Part 4 – Classes can be found here.

Currently, to declare a variable in JS the var keyword is used.

var string = 'abc';
var num = 1;

 

With ES6 come two new keywords which can be used to declare variables. They are constlet.

const

When a variable is declared using the const  keyword, the value assigned should not change.  An example of this would be in a user system where once the user is registered, their unique identifier would never change.

const userId = 'somethingUnique';

Once a const is set no changes can be made to it. JS will throw an error if this happens.

let

When a variable is declared using the let keyword, the value assigned is expected to change. An example of this would be a users password. They may at any time chose to change it.

let userPwd = 'Password123';

Variables declared using let can be changed at any time – it can be used in the say way as the var keyword.

Why?

The code is more expressive & easier to read. If you are looking at a large piece of code, it is immediately obvious which variables won’t change and which may change.

 

Check back shortly for the part 2 – Template Strings.

 

As not all browsers support ES6 code yet, Babel should be used to transpile (convert) the code into ES5 code.

 

 

Comments