Coercion and falsy values in JavaScript
Table of contents
Type Coercion
Let us first begin with the concept of type coercion in javascript. Type Coercion is the implicit conversion or automatic conversion from one data type to another data type (for eg numbers to strings or strings to numbers).
//Example 1
const firstValue = 4 + "3"; //implicit conversion
console.log(firstValue); // output: "43"
//Example 2
const secondValue = 23 * "5"; // implicit conversion
console.log(secondValue); // output: 115
Here in the first example, the number 4 is coerced to a string "4" and then concatenated with string "3". Therefore, the result is string "43".
While in the second case string "5" is coerced or converted to a number 5 and then it is multiplied by the number 23. Therefore, the result is number 115.
Truthy and Falsy values
In JavaScript, a truthy value is a value that is considered true when used in the case of a boolean context. Except for the following values:
false
, 0
, -0
, 0n
, ""
, null
, undefined
, and NaN.
All values are considered to be truthy in javascript.
/*
Try to test it with values such as " ", -34, "hello", {}, []
*/
const testTruthy = 2;
if(testTruthy){
console.log("value is true");
}else{
console.log("value is false");
}
//output: value is true
// because the value 2 is evaluated as true inside if condition
Note: JavaScript uses type coercion in boolean contexts.
Examples of truthy values in JavaScript (which will be coerced to true
in boolean contexts, and thus execute the if
block):
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (-42)
if (4.78)
if (-4.78)
I hope this article is helpful for you :)