In this article we are going to Learn Modern JavaScript [ ES6 | ES7 | ES8 ] , so as you know JavaScript is a scripting language that was introduced for building web pages alive and interactive with the user. JavaScript is also , often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.
Read My Articles on Python Google Map
What is Modern JavaScript ?
Modern JavaScript refers to the latest version of the JavaScript programming language, which includes new features, syntax and standards that improve the language’s functionality and performance. Modern JavaScript is often used in web development for creating dynamic and interactive websites and applications.
Some of the key features of modern JavaScript include:
- Arrow functions: new syntax for defining functions that allows for shorter and more concise code.
- Classes: new way of defining objects and creating object-oriented code.
- Promises: new way of handling asynchronous operations in JavaScript that simplifies code and improves performance.
- Template literals: new syntax for creating strings that allows for easier interpolation of variables and expressions.
- Destructuring: new syntax for extracting values from objects and arrays, which can simplify code and improve readability.
- Modules: new way of organizing and importing/exporting code in JavaScript that improves modularity and reusability.
In addition to these features, modern JavaScript also includes updates to the core language, such as improved support for Unicode, better error handling, and enhanced performance optimizations.
Many modern JavaScript frameworks and libraries, such as React, Angular, and Vue, rely on these new features to provide powerful and efficient solutions for building complex web applications.
What is ES ?
In the year 1996, a standards organization called ECMA (European Computer Manufacturers Association) International carved out standard specification called ECMAScript (ES) which all browser vendors could implement. And Javascript is the most well-known implementations of ES.
Versions of ES ?
There are different version of ES that are released during different years.
ES1 (1997) it was the fist edition.
ES2(1998) editorial changes only.
ES3(1999) regular expressions and try/catch added.
ES4 this version was not released because of some issues.
ES5(2009) added some new features like use strict, isArray, foreach, map, filter, reduce and some more.
ES6(2015) some new features has been added, that we will talk about this.
ES7 (2016) some new features has been added, that we will talk about this.
ES8(2017) some new features has been added, that we will talk about this.
ES9(2018)
ES10(2019)
ES11(2020)
ES6
ES6 was one of the best progress of JavaScript in recent years. after introducing ES6, the modern programming was introduced in JavaScript.
Some nice features in ES6
- Let & Const:
Before this in JavaScript we had function and global scope, after introduction let and const now JS has block scope.
1 2 3 4 5 6 7 8 9 |
let num = 5; if(num < 6 ) { let greeting = "Hello "; let greeting = "World"; console.log(greeting); } |
1 2 3 4 5 6 7 8 9 |
const num = 5; if(num < 6 ) { const greeting = "Hello "; const greeting = "World"; console.log(greeting); } |
- Template Literal
Template literals are an improvement on string concatenation that you should rarely ever combine strings with traditional concatenation.
1 2 3 4 5 6 7 8 |
let name = "Parwiz"; let lname = "Forogh"; //let fullname = "My name is " + name + " and my lname is " + lname; let fullname = `My name is ${name} and lname is ${lname}`; console.log(fullname); |
1 2 3 4 5 6 7 8 9 |
function display(name) { return `${name.toUpperCase()}` } console.log(display('parwiz')); |
- REST Operator
It is used to handle function parameters, you can use three dot (…) for this. Rest operator signify that parameter is a placeholder for any number of arguments. and rest operator is used for handling function parameters. the best thing is this that the rest parameter is of Array type.
1 2 3 4 5 6 7 8 9 |
function mynumbers(...nums) { console.log(nums); } mynumbers(9,7,8); |
- Spread Operator
Spread Operator is used with arrays and its syntax is exactly the same as that of Rest Operator. and it is used to split the content of an array.
1 2 3 4 5 6 7 |
let a = [1,2,3,4,5]; let b = [6,7,8,9]; let c = [...a, ...b] console.log(c); |
1 2 3 |
let hello = ['Hello', 'World']; console.log(hello); console.log(...hello); |
some time we need to convert a string in to list of characters, than we can use spread operator.
1 2 3 4 |
let name = "Parwiz"; console.log(name); console.log(...name); |
you can use spread operator with the objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let obj1 = { name:'Parwiz', lastname:'Forogh' }; let obj2 = { email:'par@gmail.com', phone: 123456, ...obj1 }; console.log(obj2); |
- Default Parameter
It is used for adding default values to function parameters if no value or undefined is passed.
1 2 3 4 5 6 7 8 9 10 11 |
function add(a, b = 8) { return a+b; } console.log(add(5,6)); console.log(add(7)); console.log(add(10)); |
1 2 3 4 5 6 7 8 9 |
function add(a,b = 2,c = 1) { return a + b * c; } console.log(add(2,3,4)); console.log(add(5)); |
- For .. of loop
for .. of is an enhanced version of for .. in and forEach loops.
1 2 3 4 5 |
const names = ["Parwiz", "John", "Ahmad", "Karim"]; for(let name in names) { console.log(name) } |
- Symbols
A new primitive type for JavaScript, it does not have a literal form, symbols are unique identifier. or we can say symbols are token that serves as unique id.
1 2 3 4 5 6 7 8 9 |
const symbol1 = Symbol() let name = Symbol("name") let lname = Symbol("lname") console.log(name) console.log(lname) |
- Arrow Functions
Arrow functions are also called fat arrow functions, they are one line functions and are much like Lambda functions in programming languages like Java and Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const factorial = (n) => { let product = 1; for (let i = 1; i <=n; i++ ) { product *= i; } return product; } console.log(factorial(5)); |
- Destructuring
Destructuring helps in unpacking values from an array or an object. you can use with object and arrays.
with object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const personalInfo = { name: "Parwiz", lname:"Forogh", email:'par@gmail.com', phone:345666 } const {name, email} = personalInfo console.log(name); console.log(email); |
with array
1 2 3 4 5 6 7 8 9 10 |
const displayInfo = function() { return ['Parwiz', 'Forogh', 'par@gmail.com'] } let [name, lname] = displayInfo(); console.log(`Name is ${name} and lname is ${lname}`); |
- Set & Maps
Before this in JavaScript we had just object and arrays collection, but now you can use set and map in javascript. Map holds key value pair.
1 2 3 4 5 6 7 8 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); console.log(map.get('name')); console.log(map.get('lname')); |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let map = new Map(); map.set('name','Parwiz'); map.set('lname','Forogh'); map.set('email','par@gmail.com'); for(let element of map ) { console.log(`${element[0]} : ${element[1]}`); } |
Sets are like arrays, but it stores unique values, we can not add duplicate values in the set.
1 2 3 4 5 6 7 8 9 10 11 |
let set = new Set(); set.add(1); set.add(2); set.add(3); set.add(4); for(let element of set) { console.log(element); } |
- Classes
In ES6 the keyword class was introduced, a class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Display { constructor(name) { this.name = name } } let display = new Display("Parwiz"); console.log(display); |
Add functions in your class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Display { constructor(name) { this.name = name } greeting() { console.log("Hello From Method"); } } let display = new Display("Parwiz"); console.log(display); display.greeting(); |
Class inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Animal { constructor(name) { this.name = name } speak() { console.log(`${this.name} make noise`); } } class Dog extends Animal { constructor(name) { super(name) } } let dog = new Dog("Dog"); dog.speak(); |
- Promises
promises was introduced in JavaScript ES6, and it is used for asynchronous programming in JavaScript. before Promises, async calls were handled by Callbacks. Promises resolved the Call Back Hell. a Promise is basically created when we are unsure that the assigned task will be completed or not. the Promise object represents the completion (or failure) of an async operation and its resulting value. there are different stats for a promise.
Pending : If an asynchronous function has not completed its task, the promise it returned will be in the pending state.
Resolved : Whenever the asynchronous function completes successfully, it will set the promise into the resolved state.
Error: If an asynchronous function finishes with an error, then it sets the promise into the rejected state.
and there are two callbacks that are the part of promises in a chain.
then() function is used to receive and process the data.
catch() function is used to receive and process an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
let completed = true; let mypromise = new Promise(function(resolve, reject) { setTimeout(() => { if(completed) { resolve("The promise has been completed."); } else { reject("The promise has not been completed."); } }, 3 * 1000); }); //pending undefined value function promisReport(promise) { promise .then(result => console.log(`Result : ${result}`)) .catch(error => console.log(`Error : ${error}`)); } console.log(promisReport(mypromise)); |
ES7
JavaScript ES7 was introduced in 2016, and added some new features in JavaScript.
- Exponentiation Operator
This operator raises the first operand to the power second operand.
1 2 |
console.log(3**2); console.log(4**2); |
- Includes() Function
Returns true if an array includes a value, if not returns false.
1 2 |
let number =[1,2,3,4,5,6,7] console.log(number.includes(2)); |
ES8
JavaScript ES8 was introduced in 2017, and added some new features in JavaScript.
- padStart
this method pads a string with another string at the beginning.
1 2 3 |
let name = "Parwiz"; console.log(name.padStart(10, 'd')); |
- padEnd
this method pads a string with another string.
1 2 |
let name = "Parwiz"; console.log(name.padEnd(10, 'd')); |
- Object.entries()
it is used for making a key value pair of a given object and it returns an array.
1 2 3 4 5 6 7 8 |
const info= { name:"Parwiz", lname:"Forogh", email:"par@gmail.com" } console.log(Object.entries(info)); |
- Object.values()
is used for getting object property values.
1 2 3 4 5 6 7 8 |
const info= { name:"Parwiz", lname:"Forogh", email:"par@gmail.com" } console.log(Object.values(info)); |
- Trailing Commas
Trailing commas comes at the end of the last item in a list
1 2 |
const number = [1,2,3,4,5,6,]; console.log(number); |
1 2 3 4 5 |
function add(a,b,) { return a+b; } console.log(add(4,5)); |
- Async/Await
ES8 came up with async and await keywords which can be used for asynchronous functionality in JavaScript. when an async function is called, it returns a Promise, when the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception , the Promise will be rejected with the thrown value. It is important to mention that async function works on top of promises. they use promises to return the results. and also you need to remember that async function and await works together. you can use await only inside async function. using it outside will throw an error. and await allows you to pause execution of async function and wait until promise is resolved, either as fulfilled or rejected.
1 2 3 4 5 6 7 |
async function functionName() { //function body let asyncResult = await ourAsyncFunction(); return asyncResult; } |
Multiple await
1 2 3 4 5 6 7 8 |
async function functionName() { //function body let asyncResult = await ourAsyncFunction(); let asyncResult2 = await ourSecondAsyncFunction(); return asyncResult + asyncResult2; } |
Once all await are resolved in an async function, it will be considered as completed. the first async function may have a promise or could be using a promise object and the rest will simply await till the previous one is resolved. see the example below of a promise chain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function mypromise() { return new Promise(resolve => { setTimeout(() => { resolve('Promise is resolved') }, 3000); }); } async function ourMsg() { const message = await mypromise(); //pleas wait untile this promise hase been resolved or rejected console.log(`Message : ${message}`); } ourMsg(); |
now in here using await we are going to tell that wait for a promise to resolve or reject. It can only be used inside an async function.
When you have multiple steps you will see the power of async or await.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
function FirstPromise() { return new Promise(resolve => { setTimeout(() => { resolve('First Promise Resolved'); }, 200); }); } function SecondPromise() { return new Promise(resolve => { setTimeout(() => { resolve('Second Promise Resolved'); }, 300); }); } function ThirdPromise() { return new Promise(resolve => { setTimeout(() => { resolve('Third Promise Resolved'); }, 5000); }); } async function message() { //const first = await FirstPromise(); //const second = await SecondPromise(); //const third = await ThirdPromise(); const [first, second, third] = await Promise.all([FirstPromise(), SecondPromise(), ThirdPromise()]); console.log( `${first} ${second} ${third}`); } message(); |
Practical example
1 2 3 4 5 6 7 8 9 |
async function getUser(name) { let response = await fetch(`https://api.github.com/users/${name}`); let data = await response.json() return data; } getUser('Parwiz') .then(data => console.log(data)) |
Subscribe and Get Free Video Courses & Articles in your Email