Coercion - Truthy and Fasly Values In JavaScript
Going beyond true and false in JavaScript
As JavaScript developers, we are very familiar with the Boolean data type. This data type can assume two values: true and false.
When a value is not exactly a boolean type (true or false) and you try to perform a condition with it, what does JavaScript do? Take a look at this code:
const name = "Mad Max";
if(name) {
console.log("Executed");
}
// Output: "Executed"
It might be surprising that the if statement was executed even though the value in the variable name is not a boolean. What is happening here is called Coercion. JavaScript tries to coerce (partially convert, but does not alert the value) any value that is not a boolean to a truthy / falsy value so that it can perform a given condition, like in the example above.
If a value is truthy, it is taken as the boolean true, otherwise it's falsy, so it is taken as false. There are certain rules to determine if a value is truthy or falsy:
Rules For Truthy Values:
Any number (including negative numbers) except 0
All non-empty string.
All empty and non-empty array or objects.
Rules For Fasly Values:
Number zero (0)
Empty string.
null, undefined, NaN.
Using this rules, we can tell before-hand if a value is truthy or fasly. Knowledge on truthy and falsy values can help you write shorter codes, like in this example:
const username = "";
// No understanding of coercion / truthy and fasly values
if(username === "") {
console.log("Username is empty");
}
// Understaing of coercion / truthy and fasly values
if(!username) {
console.log("Username is empty");
}
The code works the same, but you have a much smaller code in the second if statement. The username is assigned to an empty string, by using the rules above, it is a fasly value. By using the negation sign on the fasly value we get a truthy value, which execute the if statement. On the other hand, if the username was a non-empty string, it will be a truthy value, if we then add the negation sign, it will be a falsy value which means that the if statment won't execute. Another example:
const isLoggedIn;
if(isLoggedIn) {
console.log("User logged in");
} else {
console.log("User not logged in");
}
// Output: "User not logged in"
This is because by default any time you do not initialize a variable in JavaScript, it is undefined. And by using the rules above, undefined is a fasly value, therefore the else block runs.
END.