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
- Const, let and var
- Default Arguments
- Arrow Functions
- Template literals
- Map, Reduce and Filter
- Array and Object Destructuring
- Iterables and Loopings
- Rest and Spread Operator
- Object Literals
- Classes in ES6s
- Promises
- Async and Await
- “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;23/*4 Re-Initializing The Variable.5 This will throw an error, as CONST variable can't be changed6*/7x = 200;89/*10 Here 'y' variable is defined in a block.11 It can't be accessed outside the scope of this block.1213 The output of this block would be :14 115*/16{17 const y = 1;18 console.log(y);19}2021/*22 Will throw an error, CONST y is undefined23*/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;23/*4 Re-Initializing The Variable.5 This will update the value of x to 2006*/7x = 200;89/*10 Re-Initializing The Variable in different scopes.11*/1213{14 let x = 200;15}16/*17Will display 100 as output18*/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 oflet
andconst
in ES6.
1var x = 10;23for (var i = 0; i < 5; i++) {4 var x = 20;5 console.log(x); //Returns 206}78console.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 argument6 Output would be : NaN7*/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 handling8*/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}45add(); // a=5, b=10, sum = 15;67add(2, 3); // a=2, b=3, sum = 5;89add(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}45multiply(10, 4);
Arrow Functions (ES6)
1// Example 12const multiply = (x, y) => {3 return x * y;4};56multiply(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)23 function welcome(name){4 const greetings = 'Hello, ' + name + ' What''s up?';5 return greetings;6 }78 greet('Ishan');9/*10 Will display output as :11 Hello, Ishan What's up?12*/
1# STRING FORMATTING (WITH ES6)23 function welcome(name){4 const greetings = `Hello, ${name} What's up?`;5 return greetings;6 }78 greet('Ishan');910/*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];67const ages = people.map((person) => person.username);89console.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];67const aboveEighteen = people.filter((person) => person.age > 18);89console.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];23// 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.89console.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 Destructuring2 var person = {3 name : 'Ishan',4 age : 19',5 profession : 'Developer'6 }78 const name = person.name; // Deepak9 const age = person.age; // dipakkr10 const profession = person.profession // 123451112// Array Destructuring1314 const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];1516 const day1 = days[0];17 const day2 = days[1];18 const day3 = days[2];
Destructuring in ES6
1// Object Destructuring2 var person = {3 name : 'Ishan',4 age : 19',5 profession : 'Developer'6 }78 const { name, age, profession } = person;910 console.log(name);11 console.log(age);12 console.log(profession);1314// Array Destructing1516 const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"];1718 const [day1, day2, day3] = days;1920 console.log(day1); // Monday21 console.log(day2); // Tuesday22 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.
Iterable | Description |
Array | We can access each individual element by iterating over an array. |
Map | We can iterate over the key-value pair in a list/array. |
Strings | Strings are both iterable & array like, so we can access each character |
Sets | Collections 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];23for (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];23for (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.23function addition() {4 var sum = 0;5 for (var i = 0; i < arguments.length; i++) {6 sum = sum + arguments[i];7 }8 return sum;9}1011console.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}89console.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 the3 inbuilt Math.max() function45 Note that Math.max() function expects a list of numeric arguments, not a single array.6*/78let arr1 = [1, -2, 3, 4];9let arr2 = [8, 3, -8, 1];1011alert(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";56const person = {7 username,8 name,9 password,10 githubID,11};1213console.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.
- Class Declaration
- 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};78console.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});45promise6 .then(function (result) {7 console.log(result);8 })9 .catch(function (error) {10 console.log(error);11 });1213/*14 Result15 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!