Friday, 15 February 2019

Type Coercion In JavaScript

Before jumping over Type Coercion in Javascript, we should have an overview of how the declaration of variables happens in Javascript.

In this article, we will be discussing Type Coercion in Javascript in the following order:





Prerequisites to understand Type Coercion:



What Is Type Coercion:

  • Definition From CodeCamp:
According to CodeCampType coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion.

Different Types of Javascript Can Coerce to:

  • String
  • Number
  • Boolean
So, what happens when you perform '5' + 5 and '5' - 5 in javascript? Let's check it out:

Consider the following Example:

 console.log('Example of type coerced to a string...');  
 console.log('5' + 5);  

It produces the following output:

 Example of type coercion to a string...  
 55  

This is an example of javascript not being 100 percent sure what it should be doing. So it takes its best guess at what behavior you want. It assumes you wanna do something like "String Concatenation" and hence produces this result. This is an example where the "integer 5" is coerced to a string.


Now, Consider the following Example:

 console.log('Example of type coerced to a number...');  
 console.log('5' - 5);  
 console.log('5' - 6);  
 console.log(6 - '5');  

It produces the following output:

 0  
 -1  
 1  

Here, javascript assumes you wanna do something like "Integer Subtraction" because there is nothing like subtraction of strings and hence produces this result. This is an example where the "string 5" is coerced to a number.

And the last one is where the type is coerced to a boolean which we have already covered here Truthy and Falsy Values in Javascript


Major Takeaways:

Type Coercion in this fashion is typically something we want to avoid because we're going to get extremely inconsistent behavior.

However, Type Coercion also helps in getting our code successfully run which would otherwise have generated tons of errors in many cases.

So what's the solution? Actually, we can manage this by changing the way we perform equality checks between expressions.

Consider the following Example:

 console.log('5' == 5);  
 console.log('5' === 5);  

It produces the following output:

 true  
 false  


As one can see, checking equality works out of the box when we use "===" in place of "==". This is always advisable to use triple equality sign in place of double equality sign while checking equality.


If you have any doubts, write down in comments so that we can discuss that further. Thanks!

No comments:

Post a comment