Modern Javascript — Part 2

In this article, we are going to learn another valuable concepts related with the Javascript programming. Let’s start with something your’re familiar with if you have done works with Javascript. If not, you are going learn them. However, I will provide a great explanation to enhance your knowledge on this area.

🔥class

  • In 2015, ECMAScript 6 introduces Javascript classes. In java, we define our constructor of the class with the class name. But in Javascript (JS), we have used “constructor” keyword to make the constructor with the paramerters without defining any local variables for the class.

The output:

Then I override the display function with emp2 object at the runtime as follows.

The output:

So, you will see here, we can have all 3 output as intended which is very convenient. Because, we can dynamically change the output with our requirements.

🔥De structuring

  • In De structuring, we can unpack the values from object or arrays in to variables easily.

Case1:

Instead of writing single lines to get the values of both PI and SQRT value of 9, we can use second way easily.

Case 2:

We can consume only the required properties of the object to perform our function.

You can see here, although Student consumes so many properties, we can consume 3 of them as we required.

Case 3:

We can have separated array from the existing one by using “…”. Let’s see with the example.

Merging 2 arrays:

Like this we can copy one object to other object as well.

🔥Promise

  • In JS, we can use promise to handle the one function after getting results from the promise object. The function waits for results from promise object is named as call-back function.
  • In the above code sample, you can see that we need to get the length of data after fetching the “https://nirodhajayaweera1993.medium.com/”.

The output:

  • Let me create another function and called fetchWebpage() without specifying “.then”.

The output says as “undefined”. Because, after we are invoking fetchWebpage(), we do not wait for its completion and we tell to print the response on console about length of responsedata.

  • Also, instead of using “.then” we can use 2 keywords known as “await” and “async”. Let me do this with my code sample.

The output:

  • What happens here is, “awaits” tells our function to wait until promise resolves.

I hope, you can get a very clear understand about the mentioned keywords of Javascript through this article.

Stay Safe !!!

References:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store