CoffeeScript Does Not Allow Loose Equality

Today learned that CoffeeScript doesn’t allow loose equality, so, whenever you use == or is it will compile to JavaScript’s === and that’s by design!

First let me remind what is loose equality in JavaScript.

Loose equality

Loose equality (“double equals”) compares two values for equality, after converting both values to a common type. After conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions).

More on equality operators: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality

Why CoffeeScript doesn’t allow it?

Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles == into ===, and != into !==. In addition, is compiles into ===, and isnt into !==.

And what if you need it?

Perform type conversion explicitly

Here is few examples:

1
2
+a is +b # numerical comparison
"#{a}" is "#{b}" # string comparison

Or with the old good JS functions:

1
2
Number(a) is Number(b) # numerical comparison
String(a) is String(b) # string comparison

Prefer loose equality?

No problem, you can use embedded JS like this:

1
`a == b` # loose equality

More on Embedded JavaScript here:

http://coffeescript.org/#embedded

Conclusion

Which ever approach you choose, the only important thing is to make sure that you know what you’re doing! ;)

Comments