Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type coercion in JavaScript

Tags:

javascript

I guess I kind of know the differences between == and === in JavaScript, it is that == will do type coercion when compare but === will not. I understand the following code will be true:

console.log(true == "1");

but when the code below is false?

console.log(true == "true");
like image 338
photosynthesis Avatar asked Oct 27 '15 16:10

photosynthesis


People also ask

What are the types of coercion?

And still there are only three types of conversion: numeric, string and boolean. coerced to true , no matter if an object or an array is empty or not. Objects are converted to primitives via the internal [[ToPrimitive]] method, which is responsible for both numeric and string conversion.

What is the difference between type conversion and type coercion?

Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.

Is JavaScript supports automatic type coercion?

Does JavaScript support automatic type conversion? Yes. It's usually called type coercion, but conversion is perfectly accurate.

What is implicit coercion in JS?

Implicit coercion happens when JavaScript coerces the value type to the expected type under the hood. This type of coercion happens without the developer noticing. Explicit coercion happens when we want to coerce the value type to a specific type.


2 Answers

When you loosely compare a boolean with a value of another type, the boolean is coerced into a number.

And when you compare a number and a string, the string is coerced into a number.

The full rules are explained in The Abstract Equality Comparison Algorithm

The process is like this:

true == "true" ─┐
                ├─ Number(true)   // 1
 1   == "true" ─┤
                ├─ Number("true") // NaN
 1   ==  NaN   ─┤
                ├─ // Comparing with `NaN` always produces `false`
   false       ─┘
like image 168
Oriol Avatar answered Sep 21 '22 21:09

Oriol


The boolean operand is converted into a numeric value and strings are converted into a numeric value since one operand is a number.

We end up with 1 == NaN. If either of the operands is NaN, the equal operator always returns false.

like image 38
BinaryProphet Avatar answered Sep 23 '22 21:09

BinaryProphet