Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 17, 2020 08:34 am GMT

Fun with Javascript tricks

In this post, we are going to learn about some fashionable javascript tricks. I was excited by these tricks. I believe that you will also be excited by the end of this post
Image

1) Optional Catch Binding

As a web developer, we should handle errors in our application. For instance, while making the API request with async/await we can come across the case of errors. Consider the below code

async function getDetails() {   try {      let result = await fetch('/getdetails');      console.log(result);   } catch (e) {      console.error('Error:', e);   }}

In this code, if the API fails it will throw an error and we are catching that error. Though, while think about the common error, we don't need to catch the error.

async function getDetails() {   try {      let result = await fetch('/getdetails');      console.log(result);   } catch {      console.error('Seems we got an issue in our end. Can you try after sometime?');   }}

Before optional chaining(ES10/2019), it's not possible. we should catch the error even though it's not used.
Browser supported versions are here.

2) JSON stringify format

We all know that JSON.stringify will convert the JS object into the JSON string. But the question is can you able to read the given JSON string? consider the below code

    let obj = {      Name: 'Alwar',      Age: 23,      Degree: 'B.E(ECE)',      Hobbies: 'Working in Web Apps, Drawing, Playing cricket,'      Country: 'India'    };    JSON.stringify(obj);

It will give the output as

"{"Name":"Alwar","Age":23,"Degree":"B.E(ECE)","Hobbies":"Working in Web Apps, Drawing, Playing cricket","Country":"India"}"

The above string is hard to read right? What should we do to improve readability? . Don't worry we have the option in JSON.stringify method. That is we can write the above code as

JSON.stringify(obj, null, 2);

Now we can get the output as

"{  "Name": "Alwar",  "Age": 23,  "Degree": "B.E(ECE)",  "Hobbies": "Working in Web Apps, Drawing, Playing cricket",  "Country": "India"}"

For more information about JSON.stringify kindly refer this

3) event.currentTarget

I hope most of us working with events. While getting the element from the event object we can use event.target to make the modifications to that particular element. But if we have cases like below, then what should we do?

Here we have outer-div(red), intermediate-div(green), and the inner-div(blue). I want to change the color of the outer-div as gray. For that, I am using an event.target method. But if we click on the intermediate-div(green), and the inner-div(blue), then it will change into the gray color instead of the outer-div(red) to be in gray. Here event.currentTarget comes into play .

Now if we click on the intermediate-div(green) and the inner-div(value), then it will not change into the gray color. Against, it will change the outer-div(red) as gray. That indicates it will give the element to which the event handler has been attached.

4) Promise.any()

This method will return a single promise that resolves with the value from that promise as soon as one of the promises in the iterable fulfills. You can understand this by one practical use case. consider, we should load any one of the below information while opening the web app index page

  • family information
  • education information
  • nativity information

So we should make three API calls for getting these informations.

   let familyInfo = fetch('/getfamilyinfo').then((val) => return val);   let educationInfo= fetch('/educationinfo').then((val) => return val);   let nativityInfo = fetch('/nativityinfo').then((val) => return val);   Promise.any([familyInfo, educationInfo, nativityInfo ]).then((value) => console.log(value));

It will load the first resolved promise information . Note that I am making three requests. These will be used later in my application. To improve the user experience I display at least one information.
Kindly check the browser supported versions before using this method.

5) Quick number conversion

In javascript, we have a Number method for converting the string into a number.

console.log(Number('5')) // 5

However, we can convert the string into a number by adding the + symbol in front of the given string.

console.log(+'5') // 5

6)Object.seal()

This method prevents the new properties to be added and allows the editing of the existing properties unlike in object.freeze method.

let detailsInfo = {  name: 'Alwar',  age: 23};Object.seal(detailsInfo);detailsInfo.education = 'B.E';console.log(detailsInfo);

The above code will produce the output as

{  name: 'Alwar',  age: 23}

Here I don't want to add any other properties. That's why I sealed this object. Also, remember that sealed object properties are editable.

let detailsInfo = {  name: 'Alwar',  age: 23};Object.seal(detailsInfo);detailsInfo.name = 'Alwar G'console.log(detailsInfo);

Now we got the output as

{  name: 'Alwar G',  age: 23}

If you don't want to edit the existing properties, then you can try the object.freeze method.
Thank you for reading this post . Feel free to post your comments if you want to share something.


Original Link: https://dev.to/alwarg/fun-with-javascript-tricks-jmk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To