Navigate back to the homepage

A Quick Dive Into ES6

Ishan Sharma
July 5th, 2020 · 4 min read

ECMAScript 2015 or ES2015 is a significant update to JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called ES6.

What we’ll be covering today

  1. Const, let and var
  2. Default Arguments
  3. Arrow Functions
  4. Template literals
  5. Map, Reduce and Filter
  6. Array and Object Destructuring
  7. Iterables and Loopings
  8. Rest and Spread Operator
  9. Object Literals
  10. Classes in ES6s
  11. Promises
  12. Async and Await
  13. “new” and “this” keyword

1. Const, let and var

1.1 CONST

  • Const defines a constant variable which can’t be changed throught the code.
  • Declaring a variable with const is similar to let when it comes to Block Scope.

For example

1const x = 100;
2
3/*
4 Re-Initializing The Variable.
5 This will throw an error, as CONST variable can't be changed
6*/
7x = 200;
8
9/*
10 Here 'y' variable is defined in a block.
11 It can't be accessed outside the scope of this block.
12
13 The output of this block would be :
14 1
15*/
16{
17 const y = 1;
18 console.log(y);
19}
20
21/*
22 Will throw an error, CONST y is undefined
23*/
24console.log(y);

1.2 LET

  • “let” defines a variable which can be changed anywhere throught the code.
  • It can be re-initialised but not re-declared in the same scope.
  • It has a block scope.
1let x = 100;
2
3/*
4 Re-Initializing The Variable.
5 This will update the value of x to 200
6*/
7x = 200;
8
9/*
10 Re-Initializing The Variable in different scopes.
11*/
12
13{
14 let x = 200;
15}
16/*
17Will display 100 as output
18*/
19console.log(x);

1.3 Var

  • Var keyword is an old method for declaring variables in javascript.
  • Value of variables declared with var can be changed at any point, during runtime.
  • Var has only a global scope.
  • MDN recommends to not to use var keyword after release of let and const in ES6.
1var x = 10;
2
3for (var i = 0; i < 5; i++) {
4 var x = 20;
5 console.log(x); //Returns 20
6}
7
8console.log(x); // Returns 20

2. Default Arguments

Default argument or default parameter allows you to set a default value for your function parameter/argument if no value is passed for the same.

Default Argument with ES5

1function product(x, y) {
2 return x * y;
3}
4/*
5 Let's just call the function without passing any argument
6 Output would be : NaN
7*/
8product();

Handling Default Argument with ES5

1function product(x, y) {
2 const x = typeof x !== "undefined" ? x : 1;
3 const y = typeof y !== "undefined" ? y : 1;
4 return x * y;
5}
6/*
7 Since we're handling
8*/
9product();

In a case when no parameter is passed, we have to explicitly handle the error by setting default values of a & b. This doesn’t look like a good way of handling default arguments.

Handling Default Argument with ES6

1function add(a = 5, b = 10) {
2 return a + b;
3}
4
5add(); // a=5, b=10, sum = 15;
6
7add(2, 3); // a=2, b=3, sum = 5;
8
9add(4); // a=4, b=10, sum=14 ;

Default value of A and B will be only used when no parameter is passed.


3. Arrow Functions

An arrow function is a syntactically compact alternative to a regular function expression without its own binding to this, super,

Regular Functions (ES5)

1function multiply(x, y) {
2 return x * y;
3}
4
5multiply(10, 4);

Arrow Functions (ES6)

1// Example 1
2const multiply = (x, y) => {
3 return x * y;
4};
5
6multiply(10, 4);

4. Template Literals

Template literals can contain placeholders. These are indicated by the dollar sign and curly braces. The expressions in the placeholders and the text between the backticks (“) get passed to a function. They are used to concatenate the parts into a single string.

Let’s see an example on formatting strings in ES5.

1# STRING FORMATTING (WITHOUT ES6)
2
3 function welcome(name){
4 const greetings = 'Hello, ' + name + ' What''s up?';
5 return greetings;
6 }
7
8 greet('Ishan');
9/*
10 Will display output as :
11 Hello, Ishan What's up?
12*/
1# STRING FORMATTING (WITH ES6)
2
3 function welcome(name){
4 const greetings = `Hello, ${name} What's up?`;
5 return greetings;
6 }
7
8 greet('Ishan');
9
10/*
11 Will display output as :
12 Hello, Ishan What's up?
13*/

You might be able to clearly reciprocate the main benefits of the latter approach.

RECAP

  • Template Literals are enclosed by back tick(“) instead of single or double quote.
  • Placeholders can be inserted between template literals. These are indicated by the dollar sign and curly braces.

5. Map, Reduce and Filter

Map, reduce, and filter are all array methods which were introduced in ES6. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.

Map Method

The map() method is used for creating a new array from an existing one, while passing each element of the array to a function.

For example: Let’s say we have a people array that contains multiple persons as object. But, we just need the age of each person.

How can we do that? Here’s one

1const people = [
2 { name: "Ishan", age: 19, profession: "Developer" },
3 { name: "Rohit", age: 20, profession: "Student" },
4 { name: "Bhavesh", age: 18, profession: "Enterprenuer" },
5];
6
7const ages = people.map((person) => person.username);
8
9console.log(ages); // [ 19, 20, 18 ]

Filter Method

Filter method take a function parameter which applies on each array element, then whichever element satisfies the parameter condition returns in the new array.

For example: Let’s consider that in the above people example, I only want to filter those users, who have an age of greater than 18 years.

1const people = [
2 { name: "Ishan", age: 19, profession: "Developer" },
3 { name: "Rohit", age: 20, profession: "Student" },
4 { name: "Bhavesh", age: 18, profession: "Enterprenuer" },
5];
6
7const aboveEighteen = people.filter((person) => person.age > 18);
8
9console.log(aboveEighteen);
10/* [{ name: "Ishan", age: 19, profession: "Developer" },
11 { name: "Rohit", age: 20, profession: "Student" } ] */

Reduce Method

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

For example : Let’s say we just want to find the sum of all numbers in an array

1const numbers = [1, 2, 3, 4, 5, 6, 7];
2
3// Here prevSum will contain the total sum, upto the previous iterated number.
4const sum = numbers.reduce(function (prevSum, num) {
5 return prevSum + num;
6}, 0);
7// Here '0' indicates the initial value of sum, before reducer function is exectued.
8
9console.log(sum); // 28

6. Array and Object Destructuring

Destructuring in JavaScript is a simplified method of extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts. It helps in improving the readability and performance of our code.

Destructuring in ES5

1// Object Destructuring
2 var person = {
3 name : 'Ishan',
4 age : 19',
5 profession : 'Developer'
6 }
7
8 const name = person.name; // Deepak
9 const age = person.age; // dipakkr
10 const profession = person.profession // 12345
11
12// Array Destructuring
13
14 const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];
15
16 const day1 = days[0];
17 const day2 = days[1];
18 const day3 = days[2];

Destructuring in ES6

1// Object Destructuring
2 var person = {
3 name : 'Ishan',
4 age : 19',
5 profession : 'Developer'
6 }
7
8 const { name, age, profession } = person;
9
10 console.log(name);
11 console.log(age);
12 console.log(profession);
13
14// Array Destructing
15
16 const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];
17
18 const [day1, day2, day3] = days;
19
20 console.log(day1); // Monday
21 console.log(day2); // Tuesday
22 console.log(day3); // Wednesday

7. Iterables and Iterators

ES6 introduced a new way to interact with JavaScript data structures — iteration. Here is the list of interable data types in JavaScript.

IterableDescription
ArrayWe can access each individual element by iterating over an array.
MapWe can iterate over the key-value pair in a list/array.
StringsStrings are both iterable & array like, so we can access each character
SetsCollections of values that we can iterate through elements

Please note that plain objects are not iterable.

for...of is a new feature in ES6 that can be helpful in accessing the interables element more easily. The for…of statement simply creates a loop iterating over iterable objects. For example,

Iterating using for...of

1const array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
2
3for (var item of array) {
4 console.log(item);
5}

Iterating without using for...of

1const array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
2
3for (var item in array) {
4 console.log(array[item]);
5}

As clearly depicted above, in the latter case we can access interable elements directly with for…of method more easily.


8. Spread and Rest Operator

Spread and Rest Operators are denoted by ... three dots. These three dots can either be used as Rest Parameter or Spread Operator.

Rest Parameter
It simply collects all the remaning arguments into an array and pass them one by one. Hence, allowing a function to be called with any number of arguments, no matter how it is defined.

Without Using Rest Parameter

1// Function to print sum of numbers.
2
3function addition() {
4 var sum = 0;
5 for (var i = 0; i < arguments.length; i++) {
6 sum = sum + arguments[i];
7 }
8 return sum;
9}
10
11console.log(addition(1, 2, 3, 4, 5, 6, 7, 8, 9)); // 45

Here arguments is a special array-like object that contains all arguments by their index.

Using Rest Paramter

1function addition(...numbers) {
2 let sum = 0;
3 for (let i of numbers) {
4 sum += i;
5 }
6 return sum;
7}
8
9console.log(addition(1, 2, 3, 4, 5, 6, 7, 8, 9)); // 45

Spread Operator

  • Using the spread operator, we can expand array/object/string into a single list or other element.
  • Spread operator is exactly the reverse of Rest operator, instead of collecting arguments into an array, it expands an array’s elements.

For example

1/*
2 Let's say we want to find the maximum number in two arrays using the
3 inbuilt Math.max() function
4
5 Note that Math.max() function expects a list of numeric arguments, not a single array.
6*/
7
8let arr1 = [1, -2, 3, 4];
9let arr2 = [8, 3, -8, 1];
10
11alert(Math.max(...arr1, ...arr2)); // 8

9. Object Literals

Object literals are used to create an object in javascript.

  • Object can be initialised by directly using the variable name. See Example 1 below.
  • Object’s method in ES5 require function statement. This is no longer required in ES6, you can directly return statement. See Example 2 below.
  • Object literals key in ES6 can be dynamic. Any Express can be used to create a key.

Let’s see object literals in action, through an example.

Object Literals with ES6

1const username = "ishandeveloper";
2const name = "Ishan";
3const password = "SecretNuclearLaunchCode";
4const githubID = "https://github.com/ishandeveloper";
5
6const person = {
7 username,
8 name,
9 password,
10 githubID,
11};
12
13console.log(person.username);
14console.log(person.githubID);

10. Classes in ES6

Classes support prototype-based inheritance, constructors, super calls, instance and static methods

There are two ways to define classes in JavaScript.

  1. Class Declaration
  2. Class Expression

Class Declaration

In order to define class using-declaration method you need to use class keyword followed by className. The class name must start with Capital letter.

1class Rectangle {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6}

Class Expression

Class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class’s body.

1let Rectangle = class {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6};
7
8console.log(Rectangle.name);

11. Promises


For supporting asynchronous programming, JavaScript uses a callback. However, the callback implementation has a major problem which is called as Callback hell. Promises come to rescue to solve the problem of callback hell.

Promises are a pattern that greatly simplifies asynchronous programming by making the code look synchronous and avoid problems associated with callbacks.

A Promise has three states.

  • pending: Initial state, neither fulfilled nor rejected.
  • fulfilled: It means that the operation completed successfully.
  • rejected: It means that the operation failed.
1let promise = new Promise(function (resolve, reject) {
2 setTimeout(() => resolve("Success ! "), 2000);
3});
4
5promise
6 .then(function (result) {
7 console.log(result);
8 })
9 .catch(function (error) {
10 console.log(error);
11 });
12
13/*
14 Result
15 Success !
16*/

DISCLAIMER : Some of the examples and explanations above are inspired from different sources, and rephrased to some extent in my own words, that help me understand the concepts better, all the credit belongs to the respective authors.

That’s it for now, catch you guys in the next one!

Join my mailing list and get notified about new blogs

Be the first to receive my latest content with the ability to opt-out at anytime. Of course, I promise that I won't spam your inbox or share your email with any third parties.

More articles from Ishan Sharma

Building a Wikipedia Search Engine App with JS

Let's put our Javascript skills to the test, we won't use any 3rd party libraries, just pure vanilla javascript.

June 7th, 2020 · 4 min read

Google Foobar 2020

My experience and thoughts on completing the Google Foobar Challenge.

June 5th, 2020 · 11 min read
© 2020–2024 Ishan Sharma
Link to $https://twitter.com/ishandeveloperLink to $https://github.com/ishandeveloperLink to $https://www.linkedin.com/in/ishandeveloperLink to $https://stackoverflow.com/users/13219775/ishandeveloperLink to $https://medium.com/@ishandeveloper