Modern Javascript

Ramsunthar Sivasankar
Nerd For Tech
Published in
11 min readJun 24, 2021

--

(source: https://pureinfotech.com/set-print-screen-key-screenshot-screen-sketch-windows-10/)

you might have learned javascript here and there some people might have learned in their school IT subject. But most of the developers started to learn JS when the stacks like MEAN and MERN came into the picture. Because on that point onwards JS has changed in many aspects. Ecma is the foundation of JS. Each and every developer must know the fundamental of JS. So lets talk about some of the modern concept of JS.

Scope

There are 3 ways of declare a variable in JS, one is using var keyword next one is let and other one is const but what is the difference ?

1-scope.js

When considering the above code, it will give the output as follows when u run this code,

i =0
i =1
i =2
i =3
i =4
i =5
i =6
i =7
i =8
i =9
k =9

but when you use let instead of var while declaring the variable “k” in the line number 2 (let k =i)then what will happen ? You will get something like this 👉 ReferenceError: k is not defined

Because the variable that defined with let key word will not visible outside the scope. So as a best practice, its better to use the let keyword to declare the variable in a lengthy scripts or in multiple function in a project. It makes debugging easier.

Const

If you have used const in the above scenario, you will get the same response as the let gave but for a different reason. Lets see why,

2-const.js

if you run this code you will get an TypeError because we are trying to change the constant variable.

2-const.js

If you run this code then you will get [ 10, 20, 30 ] as an output. Because const only protecting a variable which is not object or array. So you can change the array as the above code.

Arrow Function

We usually write a function in JS like,

function functionName (parameter) {
//to-do
}

But there are new ways we can write a function in JS such as,

const functionName =(parameter) => {
//to-do
}

or if a function has only one line inside the body we can write it as,

const functionName = (parameter) => //to-do;

This is called Arrow Function. lets see an example,

3-arrowF1.js

If you run the above code you will get the output as follows,

10
10
10
4

This is the beauty of arrow function.

Behavior of Arrow function

Even though arrow function is a alternative way of writing a function in modern JS, there are some differences in how these two behave. Lets see with a simple example,

4-arrowF2.js

So if you looks closely in the above code segment, print is a object variable which has two function function1 (normal function) and function2 (arrow function). What will be the output when we run this above code? you will get,

1st function : { function1: [Function: function1], function2: [Function: function2] }
2nd function : {}

Because in the normal function, this keyword represents the object that called the function and at the same time in the arrow function, this keyword represents the object that defined the arrow function. click here to learn more on this keyword. So don’t get confused.

Object

Now lets look into the things that we can do in JS objects.

5-object.js

in this above code, demoObject is a object which supposed to have a key : value pair. But I used a num without a pair. If I run this you will get,

1.4142135623730951

Because I have already declared and used other module (Math) to that variable, so in that case we don’t need to specify it as a key : value pair. That is actually similar to num:num; but that is not necessary to put.

Lets look at an another example,

5-object.js

In this above code, [status] is the key on line number 5. That is called dynamic property. It means we can set a place holder as a key in the object if the key value is a dynamic. lets say you want to send an object to the user through the service and you are informed that the key value is not static. In that case you can set a place holder as a key and then get the value from the user. So if run the code you will get,

{ key: 'value', service: 'approved' }

For the demo, I have set the place holder value in the line number 1 as service.

Freeze method

lets look at another cool feature,

6-freeze.js

In this above code, I defined an object with one key with empty value and I am setting the value and printing it (forget about the comment for the moment). Then I am again changing the value and printing the object again. So if you run this you will get,

{ x: 'alpha' }
{ x: 'beta' }

as an output. So what will happen if I uncomment the line number 4 and run it again then what will be the output ?

{ x: 'alpha' }                                 
{ x: 'alpha' }

You will get this as an output. Because if you use freeze, it will not allow to change the value no matter what. So while working, let say you want to keep an object value same as in all the services in an application then you can freeze the value and pass it in the services. So what do thing of the following,

6-freeze.js

So you think the value of the object will look like once I print it,

{ x: ‘alpha’, y: 5 }
{ x: ‘alpha’, y: 5 }

But no, if I run the code the output will be,

{ x: 'alpha', y: { z: 5 } }
{ x: 'alpha', y: { z: '444' } }

Because you need to keep in mind that Object.freeze() method only freeze the first level values(not the first value its first level) and it won’t freeze inner level object values.

Template

Lets look into the template,

7-template.js

If you run this you will get

Edward Kenway born in England

So template is not a big topic but it is used to replace the value in the execution time. These are written with the dollar sign and curly brackets. And the whole sentence should be between the backticks(``).

Classes in JS

most of the people started their IT carrier with the Java or .Net as their first OOP programming language. We used class in those languages. As you all know, that classes are templates for creating objects and in here it is JS objects. Now let see how classes are working in JS,

8-class.js

Usually in Java, we use the constructor in the same name as the class name but in here we use the keyword constructor . Even though we use name in the constructor (above code) we don’t need to declare as in JAVA. Most importantly we can override a function when calling through an object. So if you execute the above code, you will get like the following,

Connor is an employee
Edward is an Employee and Principal of VNC
This function is overridden

First 2 lines of output are expected because I have called those function from each classes . But after the overriding you can see the output as “This function is overridden”. So even though this looks exactly like Java class but in reality it mimics.

Destructuring in JS

This is a JS expression to take out values from array or properties from JS objects. If we take array destructuring, we can declare two variables separately and assign values in one line as in the following code,

9-destructure.js

So you will get,

5
10

as the output. Lets take another example, so in the following code there is a function, I have created an object with some key values and then I’ve created a function called “area” and passed one of the value of “Obj ” as a parameter.

9-destructure.js

Lets see what will happen if I run the code,

5.9049000000000005

I got 5.9049000000000005 as the output because I have logged the function with the Obj as the parameter so I don’t need to specifically mention the value of the Obj (like Obj.value). It automatically gets the value from the Obj.

So lets say we are printing as follows with the same code,

9-destructure.js

So in the above code I’ve added a function called area1 with an interesting parameter and I explain it, as I mentioned in the previous method call (area) I passed the object as the parameter but in here, I passed the object as well as key value with condition({value}, {round =3} ={}). Basically if there is any value given to the round it will take 3. So the output will come with the decimal place according to the round value. So If I run the code,

5.905
5.90490

as I mentioned above in the first console I didn’t pass any value to round so it just print with 3 decimal point and in the second console log I passed 5 as the parameter for the round variable so it prints the output with 5 decimal point.

Lets take another example with and without destructuring in file handling,

9-destructure.js

As you can see normally we require the fs module and used a variable and use the function from that variable as the above code. But using destructuring we can write it like the following,

9-destructure.js

as you can see from the above code, we don’t need any const to call the function from it and we can just directly call any methods we want. So here I used writeFile. Lets take another example,

9-destructure.js

So in the above code there are only 4 property (with one empty) with 5 values. If you run this,

10
50

In here, it skips the value for the empty property and assigned the value to d . That is why d’s value printed as 50. Lets see what will happen if we change the code a little bit,

9-destructure.js

So in here, there are two property a and otherValues and if we run the code,

10
[ 20, 30, 40, 50 ]

We know that a is 10 but the spread operator (…) used to get the rest of the values to be assigned to the otherValues property. We can use this spread operator to copy an array to another. Lets see how its done,

9-destructure.js

Nothing much only I have added these lines to that code and if we print this we will get,

10
[ 20, 30, 40, 50 ]
new array:20,30,40,50

As you can see the new object(newArr) got the copied value. And also you can use this to merge two arrays as well. This is also suitable for the objects as well and lets see how,

9-destructure.js

In this code segment, I have created a games object with some values. As you can see I have passed games object to a string and object with spread operator and If I run this,

stealth
{ name: 'Splinter Cell', character: 'sam fisher', sequel: 6 }

so the type got printed and everything else were assigned to gameDetails object. And also we can copy object just like the array using destructuring.

Promise

When we are dealing with asynchronous operations in JS (like HTTP request and response), we used callback function. But Promise is better than callback functions. In general, we can pass function as a parameter to another function. (callback is also a function). So the problem with the callback is it will create “Callback Hell” which means the code will be messy when there are so many nested functions called within functions. Promise is able to handle this kind of problem. Basically in promise, it resolves when nothing went wrong or it rejects. In other word, we use it to get synchronous output out of asynchronous process.

There are 3 states in promise such as pending, resolved , and rejected. Lets look at the code,

10-promise.js

To create a promise, we use a constructor. I set the timeout to mimic the HTTP response (it takes some time to populate). This code explains the basic idea how the promise works.

To use the promise, we have to use then() for resolving and catch() for rejecting.

10-promise.js

and if you run this you will get the following output after 3000 milliseconds,

Promise is resolved!

We also can create a function to use the previous promise like the following code,

10-promise.js

There is something called chaining, lets say there are multiple async requests, we can create a separate promise and chain it with other promise. Like creating a function and adding the new promise in the then() method like in the following code (only the then part),

...
.then(1stPromiseObject)
.then(2ndPromiseResolve)
...

Async/Await

This works with promise and make promises easier to write. If there is a function starts with the async keyword, the function will return a promise. The await works only inside the async functions. This keyword let the JS to know that hey! wait until the promise returns any results. If you use await without async, you will get syntaxError saying “await is only valid in async function”. Most importantly, this is more easier syntax than promise.then(). Lets take a look at the example (consider the previous demoPromise code),

10-promise.js

So this is the how function willl looks like with async and await. This is easy to understand comparing to other types.

I hope you have learnt lot of new JS features using this article and I have uploaded these codes in my GitHub. Click Here to check the codes. Keep learning.

References

I have referred the following YouTube videos to write this article, which was made by Krishantha Dinesh

--

--

Ramsunthar Sivasankar
Nerd For Tech

MSc student of Greenwich University || Software Engineer