Coercion in JavaScript

Here, we are going to learn the Coercion in JavaScript and understand it using Case Scenarios.
Submitted by Himanshu Bhatt, on September 15, 2018

We are going to talk about Coercion in JavaScript, it is a mouthful word but still, a lot of people do not know about it even a coercion. So what is coercion in the context of JS, my answer to will be, Sometimes the JavaScript wants to the smartest guy in the room, sometimes it is and sometimes it is not? JavaScript tries to predict and do something for you, sometimes it does it perfectly and sometimes is not able to do it so perfectly so we need to be aware where Javascript can make a mess and where can do predictions (by prediction we don't mean Machine learning or AI). JavaScript tries to become smart and try to do something for us but we don't want it to do. So it is better to understand how JavaScript will predict these things to our advantage.

Case 1:

Let's look some examples...

Example 1:

console.log('5' - 5);

Output

coercion in JS - Output 1

So it seems that JavaScript interpret '5' as an integer instead of a string. It producesan output of 0. Well, this is helpful (thank you JavaScript).

Example 2:

console.log('5' + 5);

From example 1 we can guess its output to be 6, right? Well, no..!

Output

coercion in JS - Output 2

The output is 55 which is not clearly 6 so what happened here? JavaScript took 5 as a string and concatenate it as 55.

As a proof have a look on next code snippet [code snippet 1]:

console.log(typeof('5' - 5));
console.log(typeof('5' + 5))

Output

coercion in JS - Output 3

typeof: This typeof function returns the type of the entity passed as a parameter.

Now, this is coercion, In JavaScript, we have three types of coercion, with:

  1. numbers
  2. strings
  3. Boolean

Case 2:

So the whole idea is you should never allow JavaScript to predict for you if you want to result in numbers be sure it is an integer or float, and if you want string then make sure it is string properly, otherwise these things will generate errors which are basically logical error and can not be identified by JS.

Now there is one thing in coercion, let's see another example [example 3]:

const add = true + 10
console.log(add);

If I make a constant variable add where I add '10' with 'true' (I know it is strange, let's say it is some use case scenario),

Output

coercion in JS - Output 4

Now the output is '11', JavaScript treated truly as a literal one, which is true of course. Now for false, let's see an example [example 4]:

const add = false + 10
console.log(add);

Output

coercion in JS - Output 5

Now it is obvious that false have 'zero' literal value.

In JavaScript 'true' is treated as one and 'false' as zero.

Case 3:

Now I will explain more of coercion using a use case scenario:

[code snippet 2]:

const loginDetails = []     //line 1
const loginID =loginDetails[0]     //line 2

if(loginID !== undefined) {        //line 3
	console.log('Allow user Login');
}else{      //line 4
	console.log('Auth failed');
}

Let's say we want a user's login credentials from a database and stored it in loginDeatails which we usually receive in an array format (that is in line 1). Normally we get Login details at first position (or just assume) so we stored it in loginID on line 2. To check whether we successfully we checked if loginID is whether undefined or not (line 3). Can you predict its output?

Output

coercion in JS - Output 6

It is obvious as we don't have any data inside loginID.

[code snippet 3]:

const loginDetails = []
const loginID =loginDetails[0]

if(loginID) {        //line 1
	console.log('Allow user Login');
}else{
	console.log('Auth failed');
}

Code snippet 3 is similar to code snippet 2 just with a difference in line 1 of code snippet 3 (the same line is line 3 in snippet 2). Now again if we run we will get an "Auth failed" output so loginID is treated as false (because it was undefined).

Now, what are the things which JavaScript take it as false? Well, they are:

  1. false
  2. 0 (zero)
  3. '' (empty string without spaces, else even a single space or any token inside it will be true)
  4. null
  5. undefined

Apart from these everything else is true.

That's all in Coercion which is a bit tricky.

JavaScript Tutorial »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.