ECMAScript 2015(ES6) part 1

ES6 is an ECMAScript standard that was ratified in 2015. Even though there is a significant updates made to ES5, some of the new features added are yet to be supported by V8 and browsers. Well, you can’t sit here and wait for browser support when all the cool kids are using ES6, you can use transpilers which enables you to write ES6 code and will convert it to ES5 so that browsers could understand. Check out babel tranpiler and its configurations if you want to use ES6 in your projects. I will use es6fiddle for this tutorial purpose.

Us an introduction lets discuss the new ways of variable declarations in ES6.

what is the difference among var, let and const ?

In order to see the difference between var and let variable declarations, one need to understand scope in JavaScript. Previous versions of JavaScript only supported function based scope unlike many other languages that support block based scope, but thanks to ES6 let adds block scope to JavaScript now. let’s see how this works…

In the above code snippet when we console.log variable i after the loop, i still carries the value from the for loop as the var declaration in the for loop will be hoisted to the global scope and the out put of i after the loop is 5. This happened because there is no block scope for the for loop and the same would happen had it been an if block. If you change var to let though, it will add block scope and the out put will vary. let’s see the code first

When you change the variable declaration to let, a block scope is created and the variable i is defined within the for loop only and can not be accessed out side that block, hence the out put when you try to console.log i after the loop throws an error as shown on the console.

Aside from the differences we discussed var and let have one thing in common that differentiate them from const, that is they can be reassigned a new value. If you have a variable that should not be reassigned a new value, it should be declared as const.

In the above code snippet once the variable test is declared as const it can’t be reassigned new value.

let is the new var and you should avoid using var unless for some weird reason you don’t want to have block scope and if you have a variable that you don’t want to mutate by accident you should always declare it as const.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.