DEV Community

Cover image for Fun with Javascript tricks
Alwar G
Alwar G

Posted on • Updated on

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);
   }
}

Enter fullscreen mode Exit fullscreen mode

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?');
   }
}

Enter fullscreen mode Exit fullscreen mode

Before optional catch binding(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);
Enter fullscreen mode Exit fullscreen mode

It will give the output as

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

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);
Enter fullscreen mode Exit fullscreen mode

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"
}"
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

console.log(+'5') // 5
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

The above code will produce the output as

{
  name: 'Alwar',
  age: 23
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Now we got the output as

{
  name: 'Alwar G',
  age: 23
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
shailendara profile image
Shailendara Kumar

I am new to javascript, this is really useful

Collapse
 
phamminhhaiau12035071 profile image
PhamMinhHaiAu-12035071

thank you very much. It really useful