Boolean to Number
When a Boolean is added to a Number, the Boolean value is converted to a number as it is safer and easier to convert Boolean values to Number values. A Boolean value can be represented as 0 for ‘false’ or 1 for ‘true’. Some examples of this are shown below.
Example: In this example, we are converting Boolean to number implicitly.
JAVASCRIPT
// The Boolean value true is // converted to number 1 and // then operation is performed let x = true + 2; // The Boolean value false is // converted to number 0 and // then operation is performed let y = false + 2; console.log(x); console.log(y); |
3 2
What is Type Coercion in JavaScript ?
Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number, etc. when different types of operators are applied to the values.
In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor.
These are the basic conversion of one dataType into another dataType:
Table of Content
- Number to String Conversion
- String to Number Conversion
- Boolean to Number
- The Equality Operator