Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting issues, how to use good old == instead of ===

I really like Coffeescript, but one thing that drives me crazy lately is type issues with Numbers and Strings in if statements. Normally not a problem as Javascript doesn´t care when you use ==, but Coffeescript convertes all comparisons to ===. Is there a way to get sloppy old == comparisons back? I feed stupid but I haven´t found anything on it.

The reason for it is that I converted other peoples code using the brilliant http://js2coffee.org/ to make it easier to read, but then I enter typecasting problems as == comparisons are replaced by ===. Needless to say I´m to f***g lazy to refactor the whole code ;).

like image 499
thomasf1 Avatar asked Mar 06 '12 13:03

thomasf1


2 Answers

This is by design. Quoting from the book CoffeeScript: Accelerated JavaScript Development

CoffeeScript’s is and == both compile to JavaScript’s ===; there’s no way to get the loose, type-coercing equality check of JavaScript’s ==, which is frowned upon by JSLint and others as the source of many “WTF?” moments. Let’s borrow an example from http://wtfjs.com/2011/02/11/all-your-commas-are-belong-to-Array:

",,," == new Array(4) // true
There are also cases where == isn’t transitive:
'' == '0' // false
0 == '' // true
0 == '0' // true

To avoid these head-scratchers, you should perform type conversions explicitly

like image 145
asawyer Avatar answered Nov 16 '22 10:11

asawyer


As asawyer said, this is by design. If you really think you need an == comparison then you can put it in backticks:

if `foo == bar`
  alert 'Sloppy comparison true'
like image 23
Jivings Avatar answered Nov 16 '22 08:11

Jivings