DEV Community

loading...
Cover image for Coercion in JavaScript

Coercion in JavaScript

godcrampy profile image Sahil Bondre ・1 min read

What is Coercion?

Coercion is the process of conversion of one data type to another.

1 + '2'
// 1 coerces to '1'
// '12'

1 + true
// true coerces to 1
// 2

1 + null
// null coerces to 0
// 1

1 + undefined
// undefined coerces to 0
// 1

'abc' + undefined
// undefined coerces to 'undefined'
// 'abcundefined'

1 < 2 < 3
// => true < 3 (left to right associativity)
// => 1 < 3 (coercion)
// => true

1 > 2 > 3
// => false > 3
// => 1 > 3
// => false

JavaScript can give weird and unexpected results when comparing. Thus, it is better to use === instead of == for comparisons as === doesn't coerce.

1 == '1'
// true
// coercion

1 === '1'
// false

Coercion decisions are made by the JavaScript Engine itself.

Manual Coercion

Here's how you can manually convert to a datatype:

const number = 42;
const string = '42';

Number(string);
// Coerces to number
// 42

String(number);
// Coerces to string
// '42'

Boolean(string);
// Coerces to boolean
// 1

Conditional Statements

The conditions inside if, ternary operator, while loop etc. are coerced to Boolean.

Truthy and Falsy

Any value that coerces to true is called truthy and to false is called falsy.

There are only 6 falsy values, everything else is truthy:

  1. false
  2. 0
  3. '', "" (Empty String)
  4. null
  5. undefined
  6. NaN

Watch out for these:

Boolean({});
// true

Boolean([]);
//true

Boolean("0");
// true

null == 0
// false

And that's all folks! Thank-you for reading and have a wonderful day 😄

Discussion

pic
Editor guide
Collapse
edisonpappi profile image
Edison Augusthy

simplest way to convert a string to a number just add + in front of the string eg: +"3"

Collapse
godcrampy profile image
Sahil Bondre Author

Yea, "+" followed by any data type coerces it into Number data type. Also, using "-" followed by the data type coerces it to the negative of the Number. Point to note is that this does'nt work with other operators like *, /, %.

Thank you for letting me know about this feature! Learnt something new today 😄.

Collapse
monfernape profile image
Usman Khalil

You earned a follower. Where have you been driving these unique ideas?

Collapse
godcrampy profile image
Sahil Bondre Author

Thank you!🙂

Collapse
techdebtor profile image
sam

Thanks for the informative article! I ran the code in my Chrome console and found a difference.
1 + undefined evaluated to NaN. It looks like undefined does not get coerced to 0.

Collapse
godcrampy profile image
Sahil Bondre Author

Yup you are correct! Thank you for letting me know the mistake. I checked in chrome as well as node, both of them do evaluate it to NaN. 😄