In JavaScript, the expression `true + false` involves type coercion, where the boolean values are converted to numbers before performing the addition operation. Understanding how JavaScript handles this operation is crucial for any frontend developer, as it highlights the language's dynamic typing and type coercion mechanisms.
When evaluating the expression, JavaScript converts the boolean values to their numeric equivalents:
Thus, the expression can be simplified as follows:
true + false // evaluates to 1 + 0
The result of the addition is 1. Therefore, the output of the expression `true + false` is 1.
Type coercion is a fundamental concept in JavaScript that can lead to unexpected results if not properly understood. JavaScript automatically converts values from one type to another when performing operations. This is particularly common with arithmetic operations involving booleans, strings, and numbers.
Consider the following examples to illustrate type coercion:
console.log(true + true); // Output: 2
console.log(false + false); // Output: 0
console.log(true + false); // Output: 1
console.log(true + "1"); // Output: "true1"
console.log(1 + "1"); // Output: "11"
In the first two examples, both `true` values convert to `1`, and both `false` values convert to `0`, resulting in straightforward numeric outputs. However, when adding a boolean to a string, JavaScript converts the boolean to a string, leading to concatenation instead of arithmetic addition.
To avoid confusion and potential bugs in your code, consider the following best practices when dealing with type coercion:
Even experienced developers can fall into traps when dealing with type coercion. Here are some common mistakes to watch out for:
In conclusion, the expression `true + false` evaluates to `1` due to JavaScript's type coercion rules. Understanding these rules and following best practices can help prevent common pitfalls and lead to more robust and predictable code.