Fun with Javascript tricks
Tags: javascript, webdev, node, codenewbie
Published: 2020-09-17 08:34:13

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](https://i.imgur.com/ssY3ySr.gif)

# 1) Optional Catch Binding
&nbsp;&nbsp;&nbsp;&nbsp; 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
```javascript
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.
 ```javascript
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 catch binding(ES10/2019), it's not possible. we should catch the error even though it's not used.
Browser supported versions are [here.](https://caniuse.com/?search=optional%20catch%20binding)
# 2) JSON stringify format
&nbsp;&nbsp;&nbsp;&nbsp; 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
```javascript
    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
```javascript
"{"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
```javascript
JSON.stringify(obj, null, 2);
```
Now we can get the output as
```javascript
"{
  "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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
# 3) event.currentTarget
&nbsp;&nbsp;&nbsp;&nbsp; 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?
{% codepen https://codepen.io/Alwar-G/pen/dyMqpBp %}
&nbsp;&nbsp;&nbsp;&nbsp; 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 😎. 
{% codepen https://codepen.io/Alwar-G/pen/ExKppxw %}
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() 
&nbsp;&nbsp;&nbsp;&nbsp; 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.
```javascript
   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](https://caniuse.com/?search=promise.any) before using this method.
# 5) Quick number conversion
&nbsp;&nbsp;&nbsp;&nbsp; In javascript, we have a `Number` method for converting the string into a number.
```javascript
console.log(Number('5')) // 5
```
However, we can convert the string into a number by adding the `+` symbol in front of the given string.
```javascript
console.log(+'5') // 5
```
# 6)Object.seal()
&nbsp;&nbsp;&nbsp;&nbsp; This method prevents the new properties to be added and allows the editing of the existing properties unlike in object.freeze method.
```javascript
let detailsInfo = {
  name: 'Alwar',
  age: 23
};
Object.seal(detailsInfo);
detailsInfo.education = 'B.E';
console.log(detailsInfo);
```
The above code will produce the output as
```javascript
{
  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.
```javascript
let detailsInfo = {
  name: 'Alwar',
  age: 23
};
Object.seal(detailsInfo);
detailsInfo.name = 'Alwar G'
console.log(detailsInfo);
```
Now we got the output as 
```javascript
{
  name: 'Alwar G',
  age: 23
}
```
If you don't want to edit the existing properties, then you can try the [object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) method.
Thank you for reading this post 🙏. Feel free to post your comments if you want to share something.