Type Coercion in JavaScript – Well Explained

Hi Geeks! In this article, we going to see about Type Coercion in JavaScript. Most of the people who familiar with JavaScript still have doubt in this topic.

Initially, type coercion in JavaScript looks confusing. But when we approach this by using simple examples, it becomes easier to understand.

Before going to the examples, let’s see what is type coercion.

What is Type Coercion?

JavaScript can convert data types behind the scenes to complete an operation. This is known as type coercion.

Type coercion can lead to unexpected values in your code and also cause errors.

Therefore, whenever we check if two values are equal, it is better to use strict equals operators === and !== rather than == and != as these strict operators check that the value and data types match.

Why Type Coercion occurs?

This JavaScript is a very flexible language. When you try to convert one data type into another, instead of getting error in certain cases it will do the job for you and you might get some unexpected results.

This is because, JavaScript tries to be little bit smart and tries to do something for you.

=== vs ==

To understand type coercion better, we must have good knowledge of == and === operator.

Is Equal To (==)

This operator compares two values (numbers, strings, or Boolean’s) to see if they are the same.

Example:

'Passion' == 'Programming' returns false;
Because they are not the same string.

'Passion' == 'Passion' returns true;
Because they are the same string.

It is usually preferred to use the strict method.

Strict Equal To (===)

This operator compares two values to check that both the data type and value are the same.

Example:

'5' === 5 returns false
Even though they have same values, JavaScript will return false, because they are not the same data type.

'5' === '5' returns true
Because they are the same data type and value.

Is Not Equal To ( !=)

This operator compares two values (numbers, strings, or Boolean’s) to see if they are not the same.

'Hi' != 'Hello' returns true
Because they are not the same string

'Hi' != 'Hi' returns false
Because they are the same string

Strict Not Equal To ( !==)

This operator compares two values to check that both the data type and value are not the same.

'5' !== 5 returns true
Because they are not the same data type

'5' != '5' returns false
Because they are the same data type and value

Because of type coercion, the strict equality operators === and !== result in fewer unexpected values rather than == and != do.

When we use == the following values can be considered equal: false, 0 and ‘ ‘ (empty string). However, they are not equal when we use the strict operators.

Although null and undefined are both falsy, they are not equal to anything other than themselves. Again, they are not equivalent when we use strict operators.

Although NaN is considered falsy, it is not equal to anything. It is not even equivalent to itself. Since NaN is an undefinable number, two NaN cannot be equal.

Also when you go for JavaScript interview you might get one of these questions even though you know JavaScript very well you may not be able to answer that. So, understanding these examples, will really help you to crack those questions.

When you try to add number and string, JavaScript first thinks what is easy to convert. For JavaScript, it is very easy to convert any number to a string than converting string to number. So JavaScript always takes an easy path.

let value = 7 + '2';
console.log(value);   //72

What happens when we give, 3 + 4 + ‘3’?

The way JavaScript works from left to right, So it takes first two numbers from left, and checks, both are number, so it simply adds that, and takes one more number from right, since it is a string, now JavaScript tries to convert that number into a string.

let value = 3 + 4 + '3';
console.log(value);   //73

Let’s see some more examples to understand better,

With Boolean values, again the same concept, if i want to convert a boolean to a number is very easy.

true means literal 1
false meas literal 0

For JavaScript, to convert a number 6 or 3.. to a boolean, it is hard for that, than converting boolean to number. So JavaScript always takes an easy path.

let value = 3 + true;
console.log(value); //4

So, in the above examples, we got 4 as answer. Because JavaScript converted boolean true value to literal 1. Then it add 3 + 1 and gives 4.

Let’s make it little bit complex,

let value = 3 + true + '4';
console.log(value); //44

In the above example, JavaScript first adds 3 + true, in the case of converting boolean true value to literal 1. Then it adds 3 + 1 and gives 4.

Now 4 + ‘4’, JavaScript converts the number into a string and gives 44.

Boolean and string

For JavaScript, it’s easy to convert boolean to string than string to boolean.

let value = true + '4';
console.log(value);  //true4

What happen if I try to convert string to a number?

let value1 = Number('Mei');
console.log(value1); //NaN

let value2 = Number('2');
console.log(value2); //2

In the value1, we got NaN. Because, for JavaScript it is very difficult to convert ‘Mei’ into a number. So it returns NaN.

In the value2, we got 2. For JavaScript, it is easy to convert ‘2’ to 2.

Number to Boolean

let value1 = Boolean(1);
//value1 = true;

let value2 = Boolean(0);
//value2 = false;

What happen, If I convert number 6 to boolean?

let value = Boolean(6);
//value = true;

In the above example, we got true. Because, while converting number to boolean, only one number will return false, that is 0.

Other than 0, all numbers will return true.

String to Boolean

let value = Boolean('mei');
//value = true

let value1 = Boolean('10000');
//value1 = true

let value2 = Boolean('');
//value2 = false;

All the string returns true when converting string to boolean, except empty string.

When we convert empty string to boolean, it returns false.

undefined to Boolean

let value = Boolean(undefined);
//value = false;

null to Boolean

let value = Boolean(null);
//value = false

So null, undefined, ‘ ‘ (empty string), 0 gets false.

Based on the above information, consider the below example, how I’m going to improve my code.

Thanks for reading my article, if you found this information’s useful, please follow by blog, it will really motivates me to write more informative articles like this.

Processing…
Success!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s