Type Coercion in Javascript
Table of contents
Type coercion occurs when javascript implicitly converts a value to another data type before evaluating an expression...
by implicit, it means it happens automatically behind the scenes
Type coercion occurs in various contexts:
context of strings:
If the binary +
operator is used between a string and a primitive value(i.e data that is not an object and has no methods) like a number, the primitive value is coerced into a string.
Here is an example:
console.log("Big " + 60 )
// => "Big 60"
// 60 is convert is to string and concatenated to "Big "
context of numbers:
- The binary
+
operator triggers numeric conversion for boolean values;true
is changed to1
whilefalse
is changed to0
console.log(60 + true) // => 61
- The arithmetic division operator / triggers numeric conversion for strings:
console.log(4 / "2") // => 2
boolean context:
When a non-boolean value is used in a boolean context, javascript implicitly converts that value to a boolean data type. Some of the boolean contexts where coercion occurs are:
- the condition of an `if statement`
- the first operand of the ternary operator `?`
- the operands of the logical `&&` operator
Here are some examples:
if(0) {
// this block of code is not executed because 0 is a falsey value
}
console.log(false ? "string" : "Hello")
// => "Hello"
// false is a flasey value
console.log('false' && 2+2)
// => 4
// 'false' is a truthy value
It is important to be aware of type coercion and its various contexts in javascript, it helps guard against bugs and unexpected code behaviour.