In this Modern JavaScript Tutorial [ ES6 | ES7 | ES8 ] we want to learn about different
new features in JavaScript ES6,ES7 and ES8. so this you can check the table of content
for this tutorial in the below.
What is JavaScript ?
JavaScript often abbreviated as JS is a scripting or programming language that allows
you to implement complex features on web pages. JavaScript is high-level, often just-in-time
compiled, and multi-paradigm. also using JavaScript you can create dynamically updating
content, control multimedia, animate images, and pretty much everything else.
in this Modern JavaScript Tutorial [ ES6 | ES7 | ES8 ] tutorial we want to learn about
different features that on ES6,ES7 and ES8.
- PyQt5 Tutorial – Build GUI in Python with PyQt5
- TKinter Tutorial -Build GUI in Python with TKinter
- Working with Python Pyglet Library
- Python Speech Recognition For Beginners
- PyQtGraph Tutorial in Python
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.
What are Versions of ES ?
Name | Year | Description |
ES1 | 1997 | It was the first edition of Modern JavaScript |
ES2 | 1998 | Editorial changes only |
ES3 | 1999 | Regular expressions and try/catch added |
ES4 | Null | 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 | Changes in RegEx and Rest or Spread Properties |
ES10 | 2019 | Some new features has been added |
ES11 | 2020 | Some new features has been added |
JavaScript ES6
ES6 was one of the best progress of JavaScript in recent years. after introducing ES6,
the modern programming was introduced in JavaScript.
Let & Const in JavaScript ES6
Before this in JavaScript we had function and global scope, after introduction let and
const now JS has block scope, and it was a feature in JavaScript ES6.
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 in JavaScript ES6
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 in JavaScript ES6
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 in JavaScript ES6
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 in JavaScript ES6
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 in JavaScript ES6
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 in JavaScript ES6
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 in ES6
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 in JavaScript ES6
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 in JavaScript ES6
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 JavaScript ES6
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 in JavaScript ES6
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)); |
JavaScript ES7
JavaScript ES7 was introduced in 2016, and added some new features in JavaScript.
Exponentiation Operator in JavaScript ES7
This operator raises the first operand to the power second operand.
1 2 |
console.log(3**2); console.log(4**2); |
Includes() Function in JavaScript ES7
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)); |
JavaScript ES8
JavaScript ES8 was introduced in 2017, and added some new features in JavaScript.
padStart in JavaScript ES8
This method pads a string with another string at the beginning.
1 2 3 |
let name = "Parwiz"; console.log(name.padStart(10, 'd')); |
padEnd in JavaScript ES8
This method pads a string with another string.
1 2 |
let name = "Parwiz"; console.log(name.padEnd(10, 'd')); |
Object.entries() in JavaScript ES8
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() in JavaScript ES8
It 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 in JavaScript ES8
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 in JavaScript ES8
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)) |