JavaScript ES6 7 Awesome Features
--
I saw a lot of blogs towards ECMAScript 6 (ES2015) and I got a feeling that a lot of developers are still not very much familiar with it. Probably the main reason is the poor support in web browsers after the release. But table has turned now as lot of modern browsers now support ES6 and we also have transpilers (like Babel), which transforms ES6 sources to ES5 sources during the build process of the application. So lets get on with it.
In this blog I will cover 7 useful and interesting features of ES6, such as classes, a feature that makes it easy for developers familiar with object oriented programming to start using JavaScript. We’ll also go over typical features inspired from functional programming languages, for instance arrow functions, let, const
variables, etc.
- let and const
JavaScript has a major problem of hoisting when using var keyword for creating variables and instantiate objects. Variables declared by var have function scope and are hoisted to the top It means that a variable can be used before it has been declared.
ES6 came up with solution for the same as let and const. let and const have block scope(surrounded by {}) and cannot be used before declaration.
let can be used for all variable declarations instead of var.
const allows you to create constants (at last) like other languages. As a best practice, always use const to handle immutable data, because it uses less memory than using let.
Example:
2. template literals
Prior to ES6 strings are written in either single quotes(‘example’) or in double quotes(“example”). In ES6, strings can also be written in back-ticks (`example`). These strings are called template literals.
With single or double quotes writing large string and variable concatenation is difficult as it becomes hard to keep track. Good news is use of template literals make it easy. It supports placeholders for variables and keeps indentations/formatting from the source, which makes enhanced string substitutions and proper formatting of seemingly dangerous strings such as strings to be embedded into HTML possible with ease. Let have a look at example to better understand this.
As we see in the above example a big concatenation and formatting can be written with ease usingtemplate literals.
Note: If you need to interpolate data inside a string, you just need to use this syntax ${data} instead of +.
3. spread and Rest operators
The arguments
object is the ultimate means of capturing all the arguments passed to a function on invocation. This makes it possible to create overloaded functions that can accept varying number of arguments.
However, the
arguments
object, though being array-like, needs to be converted to an actual array before certain array operations can be carried out on it.
Here is a simple example:
This function computes the sum of any number of arguments passed to it. If the argument is not a number
, it tries to convert it to a number using the Number()
global function. It returns 0
if no argument is passed. Notice that the arguments
object was first converted to an array and assigned to the args
variable in order to use the reduce()
method.
In ES6, rest parameters were introduced. A rest parameter is simply a named function parameter preceded by three dots(...
). The rest parameter is assigned an array that contains the remaining arguments passed to a function. Here is how we can rewrite our previous sum()
function using a rest parameter:
Some important notes about Rest.
- You can only have one rest parameter for a function.
- The rest parameter, when present, must be the last parameter.
- A rest parameter is not the same as the arguments object. It only captures the remaining arguments after the other named parameters while the arguments object captures all the arguments passed to the function regardless.
- A rest parameter cannot be used in an object literal setter.
Spread Operator
Let’s say we have an array containing the scores of students in a class and we want to compute the average score of the students. Basically, we will first compute the sum of the scores and then divide the sum by the number of scores.
We can use the sum()
function we created in the previous section to compute the sum of the scores. However, the issue is that we have an array of scores and sum expects numbers as arguments.
Prior to ES6, the Function.prototype.apply()
method can be used to handle cases like this. This method takes an array as its second argument which represents the arguments the function should be invoked with.
Here is an example:
In ES6, a new operator known as the spread operator(...
) was introduced. It is closely related to rest parameters and is very useful for dealing with arrays and other iterables. With the spread operator we can compute the totalScore
as follows:
const totalScore = sum(...scores);
Hence for most of the use cases, the spread operator is a good replacement for the
Function.prototype.apply()
method.
More Example:
4. destructuring of objects and array
of object: This enables extraction of requested properties from the object and assigning them to variables of same name as properties
of array: This enables extraction of requested element from the array and assigning it to variables.
Example:
5. default function arguments
Providing values for all parameters in a functions becomes difficult at times. That’s where the default values comes in.
Example:
6. Arrow Functions
Anonymous functions can now be just written as arrow function. Arrow function uses the parent this context and doesn’t create a new for the function block.
Example:
7. classes
Which Java/C# developer doesn’t miss classes when switching to a JS project? Who doesn’t like explicit inheritance, like in Java/C# language, instead of writing magic code for prototypal inheritance? Although some JS developers complained, classes have been introduced in ES6. They don’t change the concept of inheritance. They are just syntactic sugar for prototypal inheritance.
Final thoughts
In this article I covered some useful features from ES6 (ECMAScript 6). There are other ES6-and-beyond features that should also be considered for writing improved code such as ES6 modules, promises, async functions, generators, etc. If you want some practice, you can use the sandbox for the learning process here.
Please check some useful examples here.
Thankyou Happy learning !!