Top 7 Javascript Concepts — ES6 ES2015 ECMAScript6
Since its release in 1995, JavaScript has gone through many changes. At first, it helped make webpages interactive. Then it got more robust with DHTML and AJAX. And now it is used to build full-stack applications.
But the recent and most significant update came in 2015 and is called by many names: ECMAScript 6, ES2015 or ES6
Now let us discuss some basic but very important features of ES6 to start with.
- Var, Let and Const
- Template strings
- Default parameters
- Arrow functions
- Destructing objects and arrays
- Restructuring or Object elevation
- Spread operator
Var, Let and Const
Prior to ES6, the only way to declare variable was with var keyword. But now we have few more options that provide improved functionality.
const
As name suggest, a const variable cannot be changed. The scope os const is also limited to the block on which it is declared.
var status = false;
status = true;
console.log(status)Output: true
const status = false;
status = true; //console error
Another example
function nodeSimplified(){
let a =10;
console.log(a); // output 10
if(true){
let a=20;
console.log(a); // output 20
}
console.log(a); // output 10
}
nodeSimplified();Output
10
20
10
let
let helps us to achieve lexical variable scoping. With the let keyword, we can scope a variable to any code block.
var name = “Jazz”;
if(true){
var name = “Rock”;
console.log(name); //Rock
}
console.log(name); //Rocklet lastName = “Jazz”;
if(true){
let name = “Rock”;
console.log(name); //Rock
}
console.log(name); //Jazz
Template Strings
It is an alternative way to concatenate strings. It also allows us to insert variables into a string. It doesn’t use the traditional method of using plus sign or comma.
console.log(`My name is ${lastName}, ${firstName} ${middleName}`)
Traditional way
console.log(“My name is “ + lastName + “, “ + firstName + “ “ + middleName)
Template strings honor whitespace, tabs and line breaks as well
Default Parameters
With ES6, you can define default parameters.
function PrintName(firstName, lastName=”Smith”){
console.log(`${firstName} ${lastName}`);
}
Arrow Functions
With arrow functions, you can create functions without using the function keyword. You also often do not have to use the return keyword.
var printName = function(name) {
return `My name is ${name}`;
}
Can be written as
var printName = name => `My name is ${name}`
With multiple arguments
var printFullName = (lastName, firstNAame) => `My name is ${lastName}, ${firstName}`
With multiple lines
var printFullName = (lastName, firstNAame) => {
let result = `My name is ${lastName}, ${firstName}`
return result
}
Arrow functions do not block ‘this’
Check following example. this inside setTimeout is not the object travel but windows.
var travel = {
places:[“india”,”taiwan”],
print: function(delay = 100){
setTimeout(function() {
console.log(this);
console.log(this.places);
}, delay)
}
}travel .print();
Output:
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: global, …}
undefined
To overcome this problem, we use the arrow function syntax to protect the scope of this. Following will work fine as expected.
var travel = {
places:[“india”,”taiwan”],
print: function(delay = 100){
setTimeout(() => {
console.log(this);
console.log(this.places);
}, delay)
}
}travel .print();
Output
{places: Array(2), print: ƒ}
(2) [“india”, “taiwan”]
But be careful when using arrow functions. Check following, what happens if we use arrow syntax to define print function. It won’t block the ‘windows’ this scope inside print function.
var travel = {
places:[“india”,”taiwan”],
print: (delay = 100) => {
setTimeout(() => {
console.log(this);
console.log(this.places);
}, delay)
}
}travel .print();
Output
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: global, …}
undefined
Destructuring Objects and Arrays
Destructuring allows you to locally scope fields within an object and to declare which values will be used. It is a very useful tool in functional programming and implementing immutability.
Consider burger object:
var burger = {
bread: “wheat”,
butter: “royal”,
meat: “chicken”
}var { bread, meat } = burger;
console.log(bread, meat)
Output
wheat chicken
What happened here : var { bread, meat } = burger;
This line pulls bread and meat out of the object and created local variables for them. We can also change these variables without changing our original object.
var burger = {
bread: “wheat”,
butter: “royal”,
meat: “chicken”
}var { bread, meat } = burger;
bread = “oats”;
meat: “beef”;console.log(“new :”, bread, meat)
console.log(“original :”, buger.bread, burger.meat)Output
new: oats beef
original: wheat chicken
We can also destructure incoming function arguments. Check following
var fullName = {
lastName: “Simth”,
firstName: “Will”
}var print = ({lastName}) => {
console.log(`Name is ${lastName}`);
}print(fullName);
Output
Name is Smith
Without destructuring, the output is unexpected
var fullName = {
lastName: “Simth”,
firstName: “Will”
}var print = lastName => {
console.log(`Name is ${lastName}`);
}print(fullName);
Output
Name is [object Object]
Restructuring or Object Elevation
It is opposite of destructuring we discussed in last section. We can grap variables and turn them into an object.
var lastName = “Simth”;
var firstName = “Will”;var fullName = { firstName, lastName }
console.log(fullName);
Output
{firstName: “Will”, lastName: “Simth”}
We can also structure object methods
var lastName = “Simth”;
var firstName = “Will”;
var print = function () {
console.log(`Name is ${this.lastName} ${this.firstName}`);
}var fullName = { firstName, lastName, print }
console.log(fullName.print());
Output
Name is Simth Will
But with Arrow function we discussed, will give us unexpected results:
var lastName = “Simth”;
var firstName = “Will”;
var print = () => {
console.log(this);
console.log(`Name is ${this.lastName} ${this.firstName}`);
}var fullName = { firstName, lastName, print }
console.log(fullName.print());
Output
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: global, …}
Name is undefined undefined
undefined
Spread Operator (…)
Spread operation is one of the backbone of functional programming. It can perform several different tasks, and I cannot think of writing high performance, immutable code for ReactJS applications with this operator.
To start with, it can combine two arrays
var countries = [“India”, “Taiwan”, “Japan”];
var cities = [“Delhi”, “Taipei”, “Tokyo”];
var places = […countries, …cities];console.log(places);
Output
[“India”, “Taiwan”, “Japan”, “Delhi”, “Taipei”, “Tokyo”]
Now lets try to get the last element of countries array, old way. Here the original array is actually reversed.
var countries = [“India”, “Taiwan”, “Japan”];
console.log(countries);
var [last] = countries.reverse();
console.log(last);
console.log(countries);Output
[“India”, “Taiwan”, “Japan”]
Japan
[“Japan”, “Taiwan”, “India”]
But using spread operator
var countries = [“India”, “Taiwan”, “Japan”];
console.log(countries);
var [last] = […countries].reverse();
console.log(last);
console.log(countries);Output
[“India”, “Taiwan”, “Japan”]
Japan
[“India”, “Taiwan”, “Japan”]
It can also help in customizing the selection
var countries = [“India”, “Taiwan”, “Japan”, “Korea”, “HongKong”];
var [first, …rest] = countries;
console.log(first);
console.log(rest);
console.log(countries);Output
India
[“Taiwan”, “Japan”, “Korea”, “HongKong”]
[“India”, “Taiwan”, “Japan”, “Korea”, “HongKong”]
Spread operator can also be used for objects in a similar manner we used it with arrays.
var burger = {
bread: “wheat”,
butter: “royal”,
meat: “chicken”
}var drink = “coffee”;
var breakfast = { drink, …burger };
console.log(breakfast);
Output
{drink: “coffee”, bread: “wheat”, butter: “royal”, meat: “chicken”}
There is so much more to cover in ES6, but this article is a good head start. My personal favorites are map(), filter(), reduce() methods. We can define class with constructors, create promises. Es6 also allows as to create, export and import modules.
I will cover these in another article. If you like this article, please don’t forget to clap.
Cheers.