Lorenzo B
Lorenzo B

Reputation: 33428

Translating CoffeeScript question mark syntax into Javascript

I have a CoffeeScript snippet that uses the Question mark operator. I need to translate into Javascript syntax. The snippet is like the following.

closeItem: (item) ->
    item.close() if item?.close and not item.isClosed

I tried to run into CoffeeScript site and the result is the following.

({
  closeItem: function(item) {
    if ((item != null ? item.close : void 0) && !item.isClosed) {
      return item.close();
    }
  }
});

Is this correct? Based on my knowledge (I'm new both on Javascript and CoffeeScript) I would translate as

closeItem: function(item) {
    if(item && item.close && !item.isClosed) item.close();
}

Am I missing something?

Upvotes: 4

Views: 4553

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075159

Your translation is good, although you might want to return the return value of item.close() (as that's what the CoffeeScript version does). CoffeeScript's translation is probably more general-purpose (for instance, it would handle a?.foo if a were the number 0). If you know item is an object, your version is fine.

Upvotes: 4

Related Questions