DEV Community

Discussion on: What is the oddest JavaScript behavior?

Collapse
 
clarity89 profile image
Alex K. • Edited

I think most of the people get confused by the language's type coercion rules and operations related to those, which are quite often not intuitive:

0 == []            // true
[] == false        // true
[] + 1             // "1"
[] + "1"           // "1"
[] - 1             // -1
[] - "1"           // -1
{} + 1             // 1 
{} + "1"           // 1
{} - 1             // -1
{} - "1"           // -1
{} + []            // 0
{} == []           // Uncaught SyntaxError: Unexpected token ==
[] == {}           // false
Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

Yeah, this is a good one. Most languages try to coerce only one side of an expression at a time, and won't ever coerce collection types to non-collection types.

Collapse
 
jwkicklighter profile image
Jordan Kicklighter

Wow, this is a new one for me. The array coercion actually caught me off guard.

Collapse
 
blindfish3 profile image
Ben Calder • Edited

The only thing that surprises me here are the loose equality comparisons between object and array; but it's not as though any sane programmer would be doing this. Otherwise almost all the others look fairly intuitive: coercion is applied to satisfy the operator being applied.

It's perhaps more useful to understand all the values that can be coerced to false; and why sometimes it's a really bad idea to use a shortcut if(isSomeValueTruthy) style condition...

edit - actually [] + 1 is weird :D