What’s New In Modern JavaScript
By: Arshad Suraj
Tags: JavaScript, Modern Javascript, Asynchronous, ES6, Js

JavaScript is a widely used scripting language which based on ECMA Script specification. Even though JavaScript hasn’t been evolved for years, the entrance of MEAN (MongoDB, Express, Angular, Node) Stack has resulted in some useful upgrades. As a result, ECMAScript 6 (also known as ES6 and ECMAScript 2015) was released in June 2015 and is now extensively utilized.

JavaScript ES6 introduces new syntax along with several new features designed to make your code more modern and readable. It enables you to do more with less code.

In this article, I’m going to cover some of the new features that have been added to ES6.

let and const

We used var to declare variables in previous versions. The var statement declares a variable that is either function-scoped or globally-scoped. This means that using the var keyword within a function creates a function scoped variable that can be accessed from within the function. Also, if we use the var keyword outside of the function, it produces a global scoped variable. These global variables can be accessed from anywhere within the code file. Duplicate var declarations will not result in an error, and the value of the variable will be changed globally.

see the codes below,

code snippet 1

In line 5 & line 12, even though var is declared within a {} block, it changes the variable’s value globally.

is declared within a block, it changes the variable’s value Even though we duplicated var within the same block (scope) on line 18, there were no errors.

Output 1

let

In ES6, The let keyword can be used to declare blocked scoped variables. These block scope variables can only be accessible from within the blocks, not globally (we cannot access it from outside the block). See the codes below,

code snippet 2

Here Variables created in lines 5 and 12 are only available within their own blocks.

Output 2

Furthermore, we cannot duplicate let inside the same scope (Block), doing so would result in an error. See the code below,

Code snippet 3

Output 3

Note:- let provides a mutable variable which means we can always change the value after we declared. for Ex:

var x=1;

x=2;

console.log(x); //result is 2

const

In ES6, there is another new keyword for declaring variables called const. But const variables can’t be reassigned once it’s been set. In other words, it provides an immutable variable except when it used with objects or arrays. See the below codes,

Code snippet 4

Output 4

Note: const protects only direct variables. It is incapable of protecting internal components. For example, it can’t protect elements within the array or elements within the object. See the codes below,

Code Snippet 5

Output 5

Arrow functions

The arrow function is fantastic, as it makes your code more readable, structured, and modern-looking. Consider below codes,

Code snippet 6

Output 6

Note: If we use the ‘this’ keyword within a regular function, the ‘this’ keyword will represent the function’s caller. But if we use ‘this’ keyword within an arrow function, that ‘this’ keyword will not represent the caller of the function. see below examples.

Code snippet 7

Output 7

Objects

See the examples below,

Code snippet 8

Output 8

Note:

In Es6, in the above code, line 7 and line 18 will store the variable’s name as ‘key’ and the variable’s value as ‘value’, in the key-value pair. When we don’t know the ‘value’ of a key-value pair while creating an object, this is a good way to go.

line 8 and line 19 will store the variable’s value as ‘key’ in the key-value pair. This is called dynamic property. When we don’t know the ‘Key’ of a key-value pair while creating an object, this is a good way to go.

Freeze

Object.freeze() is a method that is used to freeze an object. It is used to make an object immutable. therefore, we cannot add or remove or modify components of the frozen object.

Note: freeze() method will only freeze 1st level component. object’s component’s internal components will not be frozen. See the code below,

Code snippet 9

Output 9

Note: If you have an object that will be sent from service to service and you want to make sure it doesn’t modify, you can use the freeze() method.

Templates

One of ES6’s nice features is template literals. When concatenating strings or using a variable within a string, we don’t need to utilize the plus (+) operator.

Code snippet 10

Output 10

Classes

Classes are the core of object-oriented programming (OOP). ES6 allows you to create and utilize classes. See the below code,

Code snippet 11

Output 11

Note:

* In ES6, we use ‘constructor’ keyword to declare a constructor. * It is not necessary to declare an instance variable in order to store an instance variable. all we need to do is assign the value within the constructor. (Refer line 3&4) * Same as java we use ‘extends’ keyword to achieve inheritance. * We use super() method to call parent’s constructor. * The most coolest feature in class is we can override a function when we call the object (Refer line 26)

Destruction

Destructuring is the process of breaking a structure. Destructuring data structures means unpacking individual values from the data structure in the perspective of programming. Destructuring can be used on an Object or an Array in ES6. Consider the codes below,

Code snippet for destruction

Note:

In the code above, Line 8 unzips the person object and assigns values to each variable. If the name of a variable matches the object’s one of the key, the value for that key will be stored in that variable.

Line 19 will assigns the values for the variable based on the order of the array.

Line 28 assigns the variable’s values based on the array’s order. After assigning, the entire elements that remain in the array will be copied to a new array (c1).

line 33 will duplicate the array.

Line 41 will merge those 2 arrays.

In line 54, even though we sent the entire object as a parameter, the object will be unzipped and those two elements of that object will be passed as the parameter to the function.

Callback, Promises, Async / Await

Node.js will run asynchronously. Here, A statement does not wait for the previous statement to complete its execution. To understand how asynchronous codes function, look at the code below.

Code snippet 12

Output 12

Note: Above, Even though function1() is called first, function2() completes its execution first, as shown in the output. This is due to the execution being asynchronous. Here, function2() does not wait for the completion of function1(). Furthermore, because line 19 executes before function1() and function2() finish, the output is ‘undefined’.

Callback function

Assume we’re in a pizza store, we order a pizza and instructing the shopkeeper to call us when pizza is ready. Then we’ll be able to continue our work. They’ll call us when the pizza is ready so we can go grab it. The callback function works in a similar way.

Assume that when we call functionA(), we pass functionB() as a parameter to FunctionA(). As a result, when functionA() is finished, it calls functionB(). This is how we can use callback functions to manage asynchronous code. Look at the code below,

Code snippet 13

Output 13

We can see that by utilizing the callback function, we can have the code execute in a specific order.

Promises

When the number of callback functions grows, it appears to get more complicated. It’s named “callback hell”. We can use promises to efficiently address this problem.

A function that takes time to complete its execution, will return a promise when we call that function. There are two possible states for a promise, they are ‘resolve’ and ‘reject’. When the function is successfully completed, we can use then() to continue our execution. If the function returns any errors, we can use catch() to handle the errors.

To illustrate how promises work, consider the example below. Let’s assume we’re sending the information about our clients’ accounts details to the system. Depending on the account type, the system will calculate the interest amount. If no records are found, the system will throw an error. Look at the codes below,

Code snippet of promises

Output to the above code

Async Await

async and await make promises easier to write. The keyword async before a function makes the function return a promise. The keyword await before a function makes the function wait for a promise. The await keyword can only be used inside an async function. Let’s convert above code using Async / Await.

getAccount(client_accounts,"John Doe") .then(account=>getInterestDetails(account)) .then(interestDetails=>getInterest(interestDetails.amount,interestDetails.rate)).then(interest=>console.log("Interest is "+interest)).catch((error)=>console.log(error));

instead of using this 👆 use this 👇

Code snippet 14

Output 14

Keep Learning ❤️