Search code examples
javascriptcoffeescriptstrictcomparison-operators

Coffeescript strict comparisons


I have the following code:

$(document).bind 'gform_confirmation_loaded', (event, form_id) =>
  if form_id == 3
    // Do stuff here
...

If I run:

typeof form_id

I get :

number

Of course the same is true for:

typeof 3

However, when the value of 3 is passed in for form_id the comparison returns false.

Coffeescript changes abstract comparison to a strict one when it compiles. If I modify the output to an abstract comparison the if statement returns true.

Given the type and value are equal, the if statement should be returning true with a strict comparison I would think?

Any help would be much appreciated.


Solution

  • I don't think you get Number for typeof 3, typeof 3 is 'number' and that's not the same thing as Number. In JavaScript, if you have a = 3 and b = new Number(3), then:

    a == b   // true
    a === b  // false
    typeof a // 'number'
    typeof b // Number
    

    Of course in CoffeeScript, == is JavaScript's === so a == b will be false in CoffeeScript. Sound familiar?

    I think your library is giving you new Number(3). If that's the case then you could get a plain old number using Number(form_id):

    if Number(form_id) == 3
      # Do stuff here