In this post we are going to examine what new features arrived in ES6 and how to use them. Assess quick examples to understand the improvements on ES5. The list of new functionality is quite big, but here weโll be focusing on some frequently used ones. We will also explore how to use best practices in our routine development tasks.
ES9 is in the discussion but ES6 is still not completely supported by all browsers. You can check the detailed compatibility table here for reference. ECMAScript(ES) is the standard, while JavaScript is the most popular language that is used to implement this standard and builds on top of it.
Scoping
ES6 introduces some welcome changes to solve common pain points with JavaScript scoping.
Let’s take an example (ES5)
function myFunction() { var myValue = "I am value"; if (1) { let myValue = "I am another value"; console.log(myValue) } console.log(myValue) }
Output:
I am another value
I am another value
However, I do not want my outer console.log statement (as in above example) to print the value of the inner variable. This is generally not the desired behaviour.
If we talk about scopes in ES5, there are two scopes in ES5: global and function.
Scope: It’s just a boundary, inside which the variable lives or can be used.
For example:
function myFunction(){ var myValue = "Don't touch, I'm a value" } console.log(myValue)
Output:
ReferenceError: myValue is not defined.
And this is because we’re trying to access the value of variable myValue out of its scope.
Though in ES5 you could achieve it by using IIFE that isn’t such easy.
So, in ES6 a keyword LET is introduced which has a local scope (yes there is another in the next section).
Let is not a replacement of var, but it is said to be a good programming standard in ES6 and typescript because it makes variables scopes predictable and easier to reason about.
Typescript: ES6 standard standard language, extension is, .ts
Let’s see how it resolves the earlier issue(s) (ES6).
function myFunction() { var myValue = "I am value"; if (1) { let myValue = "I am another value"; console.log(myValue) } console.log(myValue) }
Output:
I am another value
I am value
You should feel accomplished!! Now try a loop using let for yourself.
Another exciting addition is const, const provides the mechanism of immutability which means, the variables do not change over time.
For example:
const myConst = "my const value"; myConst = "my another const value"; Output: VM47:1 Uncaught SyntaxError: Identifier 'myConst' has already been declared at :1:1
Before any argument, I would add that, the variable is immutable but not the value it is assigned to. It means if we declare an object as const, we can change the properties of that object.
For Example:
const myConstObject = {}; myConstObject.constProp = "Const Value"; console.log(myConstObject) Output: {constProp: "Const Value"}
Looping
If you are frequently using for…in & foreach loops you may be skeptical of the introduction of for..of but believe me, youโre going to like it!.
So, why for…of arrived, definitely for..of got something better than for…in, let’s check it.
For…in (ES5):
var myCoins = [1,2,5,10]; for( let coin in myCoins){ console.log(typeof(coin)); } Output: string string string string
Yes, you read the output right. for…in loop returns a number array as string values. This can obviously confuse and create hard-to-track bugs.
For & ForEach (ES5):
Let’s see a basic example to show how forEach works:
var myCoins = [1,2,5,10,20] myCoins.forEach(function(value){ console.log(value); }); Output: 1,2,5,10,20
Yes, thatโs right, there is no number to string conversion issues. But there is a problem.
You cannot break out of the loop using break statement and move to the next iteration with continue statement.
For…of:
Introduced in ES6, for…of avoids the issues of the for…in loop, and it works with break and continue statements and even allows return from the enclosing block.
var myCoins = [1,2,5,10]; for( let coin of myCoins){ console.log(typeof(coin)); } Output: number number number number
Data Structures
Letโs start with some frequently used ones, like Set and Map.
Set: Letโs quickly cover some of the important bullet points about set.
-
- You do not store key-value pair like objects in Set, just the keys.
- No repeating values, contains distinct elements/objects.
- Example:
let myCoinSet = new Set(); myCoinSet.add('foo'); myCointSet.size // 1 myCoinSet.add('foo'); myCoinSet.size //1
-
- Set receives iterable parameter as its input.
- Example:
- Set receives iterable parameter as its input.
let myCoinSet = new Set([1, 2, 3]) - correct let myCoinSet = new Set(1,2,3) -wrong
-
-
- Or you can do like:
-
Let myCoinSet = new Set(); myCoinset.add(1) -correct myCoinSet.add(1,2,4) -wrong myCoinSet.add([1,4,5]) -wrong
-
- Set does not support random order access of elements like arrays do
- For Example:
- Set does not support random order access of elements like arrays do
console.log(myCoinSet[1]) -wrong
- Some common operations of Set:
- Remove element: myCoinSet.delete(2).
- Empty the set: myCoinSet.clear();
- Looping over Set is quite straightforward
-
- For Example:
let myCoinSet = new Set([1, 2, 5, 10]) for (let coin in myCoinSet){ console.log(coin) } Output: 1, 2, 5, 10
Map: Let’s quickly cover some of the important bullet points about the map.
- A map is a key-value pair.
- An order is maintained as they are saved so when we put loop, it prints in the same order.
Letโs do some fundamental operations using Map.
-
- Creating Map:
let myMap = new Map();
-
- Adding pairs
let myMap = new Map(); myMap.set("Name", "Carlos") myMap.set("Occupation", "Engineer" )
-
-
- Another way of adding:
-
let myMap = new Map([ [ "Name", "Alex" ], [ "Occupation", "Test Engineer" ], [ "Company", "Modus Create" ] ]);
-
- Get element by key
map.get("Name") // Carlos
-
- Checking whether key exists
map.has(โNameโ) //true
-
- Deleting by key
map.delete(โNameโ)
-
- Checking size
map.size()
-
- Empty whole map
map.clear()
-
- Looping over map is quite easy like we did for set, but here we have key-value so, it depends what you want to loop through.
- Example:
- Looping over map is quite easy like we did for set, but here we have key-value so, it depends what you want to loop through.
let m = new Map([ ["Name", "Chris"], ["Occupation", "Technical Manager"], ["Company", "Modus Create"], ["Country", "USA"] ]); 1- for(let keys of m.keys()){ console.log(keys) }
-
-
-
- Output:
-
-
Name, Occupation, Company, Country
2- for(let value of m.values()){ console.log(values) }
-
-
-
- Output:
-
-
Chris, Technical Manager, Modus Create, USA
3- for(let [value, key] of m){ console.log(`value: ${value} Key: ${key}`) }
-
-
-
- Output:
-
-
value: Name Key: Chris value: Occupation Key: Technical Manager value: Company Key: Modus Create value: Country Key: USA
Letโs discuss How Objects are different from Map
-
- In Objects you are bound to use simple keys as string, numbers or symbols but in Map you can use even array and objects.
- Map is an instance of Object not vice-versa.
- Functions as values is not possible in Map but in object itโs possible.
- Example:
var person = { name: "Carlos", workingDays() { console.log("25 days average") } }
- Using objects is preferred over map if your application has bountiful JSON operations.
- What is your experience using Objects and Maps? Please share your scenarios where you find one of them is more efficient over another. What problem could you not solve by one but not with the other?
There are many more cool and advanced features in ES6 such as Fat arrow function, Destructuring, Modules, Classes, Interfaces, Promises and Types. This is not the end of this topic. Look for the part 2 of this subject in an upcoming post.
Please leave your valuable comments & suggestions about this post.
Nikhil Kumar
Related Posts
-
Quick Practical Guide for ES6: Part 2
JavaScript ES6 features, comparison with ES5, ES6 best practices, and examples tested on Chrome developer…
-
Monad Pattern for Functional Programming in ES6
A Curious JavaScripter's Guide to Monad Pattern There are times when, on the journey to…