What are ES6 features ?

Cover Image for What are ES6 features ?
Ullas Kishan
Ullas Kishan
7 min read
  • Introduction

    ES6 or the ECMAScript 2015 is the major edition of ECMAScript language, which is introduced the year 2015. It introduced several new features, that can be useful for developers to fasten the development.

There are more than 10 feature introduced with the release 2015. I have listed the below the features and the details.

Let and const

The keywords let and const are used to define variables and constants. Before ES6, only the var keyword was used to declare the variable and this has function scope. var will be hoisted.hoisted means the variable declared using var will move to the top and this variable will be available to use before declaring.

The let variables and const have block scope which is surrounded by curly-braces "{}" and cannot be used before declaration.

E.g:-

sampleVariable = 10; // this variable used before declaring, but it is not going to throw the error
// this is restricted in let and const feature
var sampleVariable;

let and const example

E.g:-

sampleVariable = 10; // this will throw, because the operation is not allowed before decalration
let sampleVariable;

The correct usage is given below.

let sampleVariable;
sampleVariable = 10;
console.log(sampleVariable); //output 10

const - const variable must be assigned the value when declaring the variable itself and this cannot be changed.

const sampleVariable;       // empty declaration is not allowed
const sampleVariable=10     // correct
console.log(sampleVariable) // output 10

⬆ Back to Top

Arrow functions

The arrow function is another feature of ES6. This is used to write the function shorter. Arrow functions are defined using the fat arrow (=>) notation.

const add = (number1, number2) => number1 + number2;

⬆ Back to Top

Default Parameters

A function is declared with some parameters and when the function is used somewhere in the program without providing the expected params, then the compiler will throw out the error with 'undefined'. So, to prevent this situation, ES6 is allowing the programmer to set the default value. This value will take place when the programmer missed to provide the parameter.

E.g:-

const add = (number1, number2) => number1 + number2;
console.log(add()); // Error, input parameters are not provided

const add = (number1 = 10, number2 = 10) => number1 + number2;
console.log(add()); // result will be 20

const add = (number1 = 10, number2 = 10) => number1 + number2;
console.log(add(15, 15)); // result will be 30

⬆ Back to Top

Rest and Spread operators

The rest operator allow us to accept indefinite number of parameter as an array to a function.

function(param1, ...args)
{
   for(let i in args)
   {
     console.log(i)
   }

}

The spread operators used to take deep copy of JS objects.

let originalValues = ["a", "b", "c"];
let copyValues = [...originalValues];
console.log(copyValues);

⬆ Back to Top

Template literals

The template Literals use back-ticks (``) rather than the quotes ("") to define a string

let title = `template literals is using back-ticks`;

It is also allowing multiline declaration, so no more + symbol to append the lines

let title = `template 
             literals is 
             using back-ticks`;

It is also allowing the interpolation on strings.

let topic = `Template literals`;
let ECMAVersion = `ES6`;
let statement = `The ${topic} is a feature of ${ECMAVersion}`;

console.log(statement);
// The Template literals is a feature of ES6

⬆ Back to Top

Destructoring assignment

This is one of the good features of ES6. It enables us to extract the relevant details from an array or object.

// Array destructoring
let RGB = ["RED", "BLUE", "GREEN"];
let [R, G, B] = RGB;
console.log(R); // RED
console.log(G); // GREEN
console.log(B); // BLUE
// Object destructoring
const UserDetails = {
  name: { firstName: "John", lastName: "Jon" },
  phone: "8982928292",
  email: "johnjon@abc.com",
  country: "India",
};

const [name, email] = UserDetails;

⬆ Back to Top

Classes and inheritance

The class was not used in earlier JavaScript, this class. This looks the same as other object-oriented languages. To inherit the class, for others, the extend keyword is used.

class EcmaScript
{
    constuctor(feature, version)
    {
        this.feature = feature
        this.version = version
    }
    const notes = () => console.log(the ${feature} is introduced in the version of ${version})

}

let obj = new EcmaScript('Class','ES6')
obj.notes()

// the Class is introduced in the version of ES6

⬆ Back to Top

Promises for asynchronous programming

A promise function enables an asynchronous operation which will produce a result later either rejected or resolved.There are 3 states for a promise operation. Those are pending, fulfilled and rejected.

Pending - The result of the operation is not computed, so this pending will be the initial state of a Promise.

Fulfilled - The operation is completed as expected.

Rejected - The operation did not go well as expected.

Syntax

const Promise = new Promise((resolve,reject) => {....});

E.g:-

let Promise = new Promise((resolve, reject) => {
  let result = fetch(url);
  if (result.data !== undefine) {
    resolve("Success");
  } else {
    reject("Failed");
  }
});
Promise.then((message) => {
  console.log("The data is restrived successfully");
}).catch((message) => {
  console.log("error");
});

⬆ Back to Top

Symbols for creating unique object keys

Symbols, newly added to ES6, are a primitive data-type that gives a unique value (Symbol value) as an output.

E.g:-

let id = Symbol("id");

let emp={
    name:'abc'
    [id]:111
}
console.log(emp[id])

⬆ Back to Top

Iteraters and generators for iterrable objects

The iterators like the loop that we used earlier in the array. The same can be used in strings and objects with the help of for..of

const name = "devphobia";

for (const x of name) {
  console.log(x);
}

Result;
d;
e;
v;
p;
h;
o;
b;
i;
a;

The ES6 generator is a different kind of function that may be paused in the middle either one or many times and can be resumed later. When the standard function is called, the control rests with the called function until it returns, but the generator in ES6 allows the caller function to control the execution of a called function.

⬆ Back to Top

Sets and Maps for working with collections

A Set is a data structure that allows you to create a collection of unique values. Set is the collections that deal with single objects or single values. It supports both primitive values and object references.

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
console.log(colors.size);
console.log(colors);

Result
4
Set { 'Green', 'Red', 'Orange', 'Yellow' }
let map = new Map([iterable]);

The Map is a new collection type for JavaScript. It will hold any type of value like a key value pair. The map remembers the insertion order of keys.

let map = new Map([iterable]);
Related tags

More Stories

Access to fetch domain-ABC from origin domain-XYZ blocked by cors policy
Access to fetch domain-ABC from origin domain-XYZ blocked by cors policy

Cross-Origin Resource Sharing (CORS) is a security feature that lets a web page from one domain request resources from a different domain

Ullas Kishan
3 min read
Why SVG element is not reading by NVDA screen reader
Why SVG element is not reading by NVDA screen reader

SVG elements will not add the accessibility atttributes by default, so that will fail to describe by itself, and the NVDA and other screen reader required these attributes to work.

Ullas Kishan
2 min read
A Guide to Resolving Git Conflicts in Your Local Setup
A Guide to Resolving Git Conflicts in Your Local Setup

Despite being acquainted with git, many developers struggle to resolve these conflicts due to a lack of understanding of how to pull the conflict details into their local machines.

Ullas Kishan
2 min read
Unlocking the Secrets of Firebase Authentication with Google in Next.js
Unlocking the Secrets of Firebase Authentication with Google in Next.js

Firebase Authentication is one of its gems, allowing you to add user authentication effortlessly. It's secure, reliable, and comes with Google's seal of approval.

Ullas Kishan
5 min read
[Solved] Firebase auth/invalid-api-key error when setting the values in the environment variable on NextJS?
[Solved] Firebase auth/invalid-api-key error when setting the values in the environment variable on NextJS?

Why am I getting an auth/invalid-api-key error when setting the Firebase values in the environment variable on NextJS ?

Ullas Kishan
2 min read
How to setup jest test case in NextJS
How to setup jest test case in NextJS

Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.

Ullas Kishan
4 min read
[Solved] How to download SVG as PNG file
[Solved] How to download SVG as PNG file

Easist way of downloading the SVG file as PNG file is done using javascript snippet

Ullas Kishan
2 min read
Some useful GIT commands for beginners
Some useful GIT commands for beginners

To keep the code is safe and distrubuted between multiple resources that been achieved with the help of GIT

Ullas Kishan
3 min read
How to set the http response headers in NextJS websites
How to set the http response headers in NextJS websites

The importance of the http response headers are highly needed to protect the websites from hackers. If you poorly managed the response header then one day the website will be compromise to the hacker.

Ullas Kishan
3 min read
What are the different types of HTTP Security headers ?
What are the different types of HTTP Security headers ?

An HTTP header is a response by a web server to a browser that is trying to access a web page.

Ullas Kishan
4 min read
[Solved] How to create Application insight access token
[Solved] How to create Application insight access token

Application Insights is an feature of Azure Monitor and it provides application performance monitoring features. APM tools are very useful to analyse applications from development, testing and production release.

Ullas Kishan
2 min read
How to do lazy loading in ReactJS
How to do lazy loading in ReactJS

A lazy function lets you defer the loading of a components code until it is rendered for the first time. Before, it will remain in the bundle. So that we can reduce the load of the application.

Ullas Kishan
3 min read
Javascript interview questions and answers
Javascript interview questions and answers

We covered most asked questions for Javascript interview and their answers

Ullas Kishan
8 min read
How to insert emojis to the html page
How to insert emojis to the html page

we are displaying these emojis with the help of ASCII code and it is not that easy to remember because its a mix of numeric and special characters.

Ullas Kishan
2 min read
Different versions of the ECMAscript
Different versions of the ECMAscript

what are the new features among the various versions of ECMA script and what is difference

Ullas Kishan
2 min read
[Solved] How to squash the number of commits from a branch in Git
[Solved] How to squash the number of commits from a branch in Git

We can squash the number of commits from a git branch

Ullas Kishan
3 min read
[Solved] Your focus-trap must have at least one container with at least one tabbable node in it at all times
[Solved] Your focus-trap must have at least one container with at least one tabbable node in it at all times

Your focus-trap must have at least one container with at least one tabbable node in it at all times, when using dialog or modal in ReactJS or other front-end framework

Ullas Kishan
2 min read
Writing test cases for modal popup in Jest
Writing test cases for modal popup in Jest

Writing test cases for modal popup in jest

Ullas Kishan
2 min read
[Solved] Uncaught TypeError: Cannot read property 'location' of undefined
[Solved] Uncaught TypeError: Cannot read property 'location' of undefined

Cannot read property location of undefined, this is an common test cases error in react jest while using useLocation hook in your react component

Ullas Kishan
2 min read
[Solved] Missing ID attributes in markdown to html
[Solved] Missing ID attributes in markdown to html

There is a common problem when parsing the markdown file the ID attribute is missing in the element, here we found a solution to fix/overcome

Ullas Kishan
1 min read
Back to basics : Top interview logical programs in javascript
Back to basics : Top interview logical programs in javascript

It is basicall demonstrating how to find the fibanocci, amstrong, prime numbers and pyramid pattern using javascript.

Ullas Kishan
4 min read
How to read the markdown files in ReactJS
How to read the markdown files in ReactJS

Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents.

Ullas Kishan
2 min read
Some useful techniques for array operation using javascript
Some useful techniques for array operation using javascript

There are few development tips for Javascript array operation, these tips will reduce your development time.

Ullas Kishan
3 min read
How to setup auto generated sitemap in nextjs
How to setup auto generated sitemap in nextjs

For every website the Sitemap will be playing important role for SEO performance. In Ecommerce and other consumer websites also SEO have important role for developing their revenue.

Ullas Kishan
3 min read
How to know whether we are using mobile or desktop
How to know whether we are using mobile or desktop

This question is very usual, to get solve this issue by using the browser property user agent to check whether the device type.

Ullas Kishan
1 min read
What are the possible ways to create objects in JavaScript
What are the possible ways to create objects in JavaScript

What are the possible ways to create objects in JavaScript, The traditional way to create an empty object is using the Object constructor. But currently this approach is not recommended.

Ullas Kishan
2 min read