What are ES6 features ?
-
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.
ES6 (ES2015)
- Let and const
- Arrow functions
- Default parameters
- Rest and spread operators
- Template literal
- Destructoring assignment
- Classes and inheritance
- Promises for asynchronous programming
- Symbols for creating unique object keys
- Iteraters and generators for iterrable objects
- Sets and Maps for working with collections
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
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;
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
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);
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
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;
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
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");
});
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])
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.
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]);
Learn more
More Stories
Cross-Origin Resource Sharing (CORS) is a security feature that lets a web page from one domain request resources from a different domain
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.
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.
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.
Why am I getting an auth/invalid-api-key error when setting the Firebase values in the environment variable on NextJS ?
Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
Easist way of downloading the SVG file as PNG file is done using javascript snippet
To keep the code is safe and distrubuted between multiple resources that been achieved with the help of GIT
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.
An HTTP header is a response by a web server to a browser that is trying to access a web page.
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.
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.
We covered most asked questions for Javascript interview and their answers
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.
what are the new features among the various versions of ECMA script and what is difference
We can squash the number of commits from a git branch
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
Writing test cases for modal popup in jest
Cannot read property location of undefined, this is an common test cases error in react jest while using useLocation hook in your react component
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
It is basicall demonstrating how to find the fibanocci, amstrong, prime numbers and pyramid pattern using javascript.
Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents.
There are few development tips for Javascript array operation, these tips will reduce your development time.
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.
This question is very usual, to get solve this issue by using the browser property user agent to check whether the device type.
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.