Understanding the ES6 Features of JavaScript
ECMAScript 6 is abbreviated as ES6. ES6 is the sixth version of ECMAScript, released in 2015 and known as ECMAScript 2015.
Now, let’s see what’s included in ES6
Arrow functions
For writing function expressions, arrow functions provide a simplified syntax.
The function keyword, return keyword, and curly brackets are not required.
Consider an example of a function declaration:
//function declarationfunction favouriteFood() {return "I'm going to have pizza for lunch";}
Using arrow function:
const lunchMenu = pizza=> `I'm going to eat a ${pizza} for lunch`;console.log( lunchMenu("onion") );
Template Literals
String literals with embedded expressions are known as template literals. Multi-line strings and string interpolation features can be used with them. In previous iterations of the ES2015 specification, they were referred to as “template strings.”
let num1 = 2;let num2 = 3;const fullName = `${num1 + num2}`;
console.log(fullName)
Destructuring Objects
Using object destructuring, you may extract properties from objects and assign them to variables in JavaScript. Object destructuring also allows you to extract many properties in a single statement, access properties from nested objects and set a default value if the property doesn’t exist.
Let’s destructure the following object:
const employee = {name: "Kim",age: 24,department: {designation: "I am a software Dev "}}
After destructuring:
const employee = {name: "Kim",age: 24,department: {designation: "I am a software Dev "}}
const { name, age, department: { designation} } = employee;console.log(name);console.log(age);console.log(designation);
Destructuring Arrays
Data may be taken from arrays, objects, and nested objects and assigned to variables using Destructuring Assignment, a JavaScript expression that allows you to unpack values from arrays or properties from objects into distinct variables.
let [firstName, middleName, lastName] = ['Peter', 'John', 'Parkar'];console.log(lastName)// Parkar
Object Literals
An object literal is a comma-separated list of name-value pairs enclosed in curly braces in plain English. Properties and functions can be used to represent those values.
A snippet of an object literal with one property and one function is shown below.
function studentAddress(address) {const {city, state} = address;const newStudentAddress = {city,state,country: 'India'};console.log(`${newStudentAddress.city}, ${newStudentAddress.state}, ${newStudentAddress.country}`)}studentAddress({city: 'Mumbai', state: 'Maharashtra'});
For of loop
The for…of command produces a loop that iterates across iterable objects such as built-in String, Array, array-like objects (e.g., arguments or NodeList ), TypedArray, Map, Set, and user-defined iterables.
Let’s consider the following example:
const students = [{ name: "Kim", city: "Dubai" },{ name: "Peter", city: "Paris"},{ name: "Kelvin", city: "Amsterdam" }];for( const student of students ) {console.log( student.name + " lives in " + student.city );}
//Kim lives in Dubai
//Peter lives in Paris
//Kelvin lives in Amsterdam
Spread Operators
The spread operator is a new addition to the JavaScript ES6 operator set. It expands an iterable (for example, an array) into individual elements. To make shallow copies of JS objects, the spread operator is widely employed. Using this operator shortens and improves the readability of the code.
Assume you’re going to the store to get some groceries.
So you have a shopping list array with all the things you wish to purchase.
You have a basket with all of the items on your list now that you are inside the store, but you want to add a few more.
Add some new products to a new array named shoppingBasket, which will be a copy of the shoppingList array.
const shoppingList = ["bread", "milk", "butter"];const shoppingBasket = [ ...shoppingList, "tofu", "pasta"];console.log(shoppingBasket);//bread, milk, butter, tofu, pasta
Rest Operators
We can specify an indefinite amount of arguments as an array using the remainder parameter syntax. A function can be called with any amount of arguments using the rest parameter, regardless of how it was defined. In ES2015 or ES6, the rest parameter was added, which improved the ability to handle parameters.
function add(...nums) {console.log(nums);}add(7, 8, 5, 4)//[7, 8, 5, 4]
Default Params
When a value is not supplied in for a function argument, the default parameter is used to set default values (ie. it is undefined ). If a parameter is not provided in a function, its value becomes undefined. The compiler uses the default value that we specify in this circumstance.
function foodShopping( food = "tomatoes") {console.log(`I'm going to buy ${food} from the shop`);}foodShopping();
Let and Const
It turns out that const is nearly identical to let. The main distinction is that you can’t reassign a variable to a new value once you’ve assigned it to it with const. The need to remember is that variables declared with let can be renamed, whereas variables declared with const cannot.
Let’s see the example of const
const originalPrice = 50;const percentOff = 20;const salePrice = originalPrice * (percentOff / 100);console.log(salePrice);
Let’s see the example of let
let x = 15;
// Here x is 15
{
let x = 2;
// Here x is 2
}
Import and Export
One of the most important parts of JavaScript ES6 is the import and export statements. It lets you move JavaScript classes, methods, components, constants, and any other variables from one JavaScript file to another.
import { add } from './data.js';let result = add(6, 2);console.log(result);
//7
Trailing commas
Since its beginning, JavaScript has supported trailing commas in array literals, and later added them to object literals, function parameters, and named imports and exports. JSON, on the other hand, does not allow trailing commas.
function add(param1,){const example = {name: 'Tom',};console.log(example)};add(2);//{name:"Tom"}
Promises
Asynchronous operations in JavaScript are handled via promises. When dealing with several asynchronous operations, they are simple to manage, whereas callbacks can lead to callback hell and unmanageable code.
Let’s create a promise that returns some user data and throws an error when not found
const userData = new Promise((resolve, reject) => {const error = false;if(error) {reject('No found');} else {resolve({firstName: 'John',age: 32,email: 'johncreta@gmail.com'});}});userData.then((data) => console.log(data)).catch((error) => console.log(error));
Fetch
The Fetch API gives you a JavaScript interface to access and manipulate HTTP pipeline elements like requests and responses. Fetch also provides a logical location for defining additional HTTP-related notions like CORS and HTTP extensions.
Let’s consider the following-
GET the first comments value ‘https://jsonplaceholder.typicode.com/comments/1' and log its value.
POST a new comment using ‘https://jsonplaceholder.typicode.com/comments' and log its value.
fetch('https://jsonplaceholder.typicode.com/comments/1').then((response) => response.json()).then((data) => console.log(data))fetch('https://jsonplaceholder.typicode.com/comments', {method: 'POST',body: JSON.stringify({name: 'Comment 109',email: 'johnpeter@gmail.com',body: 'Hello Buddy',postId: 1})}).then((response) => response.json()).then((data) => console.log(data))
Async and Await
Async/Await was developed to make working with and writing chained promises easier. A Promise is returned by async functions. The Promise will be refused if the function returns an error. The Promise will be resolved if the function returns a value.
Let’s consider I want to print on the console a random joke from the Chuck Norris API using async and await:
const apiUrl = "https://api.chucknorris.io/jokes/random";async function getJoke() {const response = await fetch(apiUrl);const data = await response.json();console.log(data.value);}getJoke();
You can learn more about ES6 here
You can also learn about NodeJS integrations here