DEV Community

Cover image for Javascript Coercion Corner Cases
ikbal arslan
ikbal arslan

Posted on

Javascript Coercion Corner Cases

Like any other language, JavaScript also has some corner cases, so it is a good idea to learn them. today I want to show you a corner case about auto coercion.

1 < 2 < 3 // true
Enter fullscreen mode Exit fullscreen mode

In this code the answer is true. but how let's check it step by step.

step 1 -> (1 < 2) < 3  
step 2 -> (true) < 3
step 3 -> 1 < 3 // true
Enter fullscreen mode Exit fullscreen mode

In this case, the answer becomes true by chance.
let's check another one

3 > 2 > 1; // false
Enter fullscreen mode Exit fullscreen mode

Mathematically this should be true but the execution says it is false lets check the code step by step

step 1 -> (3 > 2) > 1
step 2 -> (true) > 1
step 3 -> 1 > 1 // one is not bigger than one so should be false
Enter fullscreen mode Exit fullscreen mode

Whenever you do any calculation please keep in mind the auto coercion. because math and code do not always say the same thing

Top comments (0)