Coercion is unknowingly the conversion of a datatype to another with the use of the Javascript engine. One of the few surprises in Javascript. Now, this behaves differently for various operators and data types such as:
- + Operator
- - Operator
- Boolean
- Equality signs
- Arrays
It happens mostly because of the dynamic type declaration of javascript variable. The use of var.
With the use of other programming languages such as c#, If we make use of numbers and strings as data types, then, compile-time ought to show us the error before runtime.
So let’s dive in into each instance of Javascript coercion:
- From practice, the + operator returns strings, so the Javascript coerce the operands to strings. Example: 3 + “90” will return 390
- Negative sign acts as a number, and it coerces the operand to a number instead Example: 90 - “3” will return 87
- Boolean, yes!
- The or/and logic gates
- Apple || “orange” returns Apple which is the first value for the or operator and also because it’s true.
- If it were (undefined| “”| 0| false) || “orange” then orange would be returned.
- So you can write a function such as this:
Function Whatsup(nickname){ Nickname = nickname || “Stranger.”; console.log(“Hey ” + nickname); } Whatsup();
Since nickname would be undefined and then false, the console will print out “Hey Stranger.”
- Equality checks for values and types
== checks for values, so coercion still occurs.
If (44 == “44”)
will return true but if the triple operator equality sign is used instead, it will return false. Ex:If(44 === “44”)
returns false; - The Array will return Nan for the - operator
Ex;
[“Right Now”] - [“Later”]
will return Nan(Not a Number) While[“Right Now”] + [“Later”]
will concatenate and return RightNowLater as a string
Remember the + operator always return strings as their value.
So in an instance where we have:
console.log(1 < 4 < 3);
it will return true instead of false because the javascript sees it as:
console.log(true < 3);
“true” would be coerced to 1 and when compared will be 1 < 3 which will be true.
Here are some of the weird behaviours of coercion.
They are best tackled with strict equality operator sign, ===
But then again, coercion may not only be with the comparison but also how javascript checks for a boolean value.
To check how Javascript coerce output, check out Number(“”), Number(), or Boolean(undefined) and see what it coerce to with the given results.
Ex: I can check,
boolean("0"); that will be coerce to false
Boolean(undefined); will be coerce to false
Number("3") will be coerce to 3;
Number("Hello") will be coerce to NaN
Also checking the precedence matters as well.
Thanks and that’s all about Coercion.
If you love/like, please share/comment. Thanks!
Top comments (2)
I never knew that. I had always thought it was just a quirk of JavaScript. Thanks for clearing things up!
Yes, it is because of coercion.
Thanks for reading the post.