The Equality Operator
The equality operator (==) can be used to compare values irrespective of their type. This is done by coercing a non-number data type to a number. Some examples of this are shown below:
Example: In this example, we are using == operator for cheching the type of the values.
JAVASCRIPT
// Should output 'true' as string '10' // is coerced to number 10 let x = (10 == '10' ); // Should output 'true', as boolean true // is coerced to number 1 let y = ( true == 1); // Should output 'false' as string 'true' // is coerced to NaN which is not equal to // 1 of Boolean true let z = ( true == 'true' ); console.log(x); console.log(y); console.log(z); |
true true false
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