• Janarthanan Soundararajan

A Glimpse of Modern JavaScript - Part 2

Updated: Nov 24, 2019


JavaScript is evolving rapidly. Now it has become a well-structured programming language. JavaScript started to shine almost every domain. So concurrency and data structures are more crucial to know as a modern JavaScript developer. In this blog post, we are going to see how to handle concurrency in JavaScript using Promise and async/await. And also data structures like Map and Set


Promise

The promise is one of the ways to handle the concurrent tasks in JavaScript. By using Promise, we can write the code to wait until the asynchronous task finishes. Promise constructor takes a callback function that callback function takes two arguments one is 'resolve', and another one is 'reject'.

Promise has three kinds of states such as finished or resolved, pending, and rejected. See the following code.


Async/Await

An async function helps to handle the promises more conveniently. It has more clear syntax than using 'then' to manage the promises. An async function looks like the normal JavaScript function but it has 'async' keyword before the functions. It runs the tasks asynchronously using the event loop and return the implicit promise.


async function myFunction() {

// return promise

}


The 'await' keyword use to resolve the promise, this keyword only can use inside the async function. See the following.


Map and WeakMap

Map is similar to JavaScript objects. It stores the collections of key, value pair elements. The key and value can be an object or primitive value. It remembers the insertion order of every element and has more useful methods. We can easily iterate the Map elements. The following way we can declare the Map.


let mapdata = new Map();


WeakMap is like the Map but we can't iterate the WeakMap value and it has weak reference over the elements. A key of the WeakMap must be the Object. See the following example to get a better understanding of Map and WeakMap.


Set and WeakSet

Set is similar to the JavaScript Array, but arrays will allow duplicate elements. The set will not allow the duplicate elements inside the Set. Set and WeakSet uses to store the unique values in an array-like structure. Set values can be an object and primitive values but WeakSet elements only can be an object.

Thanks for reading!


#javascript #javascriptprogramming #programming #es6 #es8 #es2015 #esnext


©2020 by Techaaroorian.

  • Pinterest
  • Twitter Social Icon
  • Facebook
  • YouTube