Vladislav
Vladislav

Reputation: 371

Coffeescript and variable check

I have the following code:

if variablename?
   alert "YES!"

l = []

if l[3]?
  alert "YES!"

It's translated into this:

var l;

if (typeof variablename !== "undefined" && variablename !== null) {
  alert("YESSS!");
}

l = [];

if (l[3] != null) {
  alert("YESSS!");
}

In Coffeescript, how would I express l[3] !== "undefined" ?

Upvotes: 0

Views: 107

Answers (2)

epidemian
epidemian

Reputation: 19219

Beware that l[3] !== "undefined" is asking whether l[3] is different from the string that says "undefined", not if its value isn't undefined. The comparison that CoffeeScript generates for l[3]? -> l[3] != null will verify when l[3] is some value different from undefined or null, which is what you want to ask most of the time :)

Upvotes: 1

Dan K.K.
Dan K.K.

Reputation: 6094

Just add typeof operator, like this:

if typeof l[3] != 'undefined'
  alert 'Yes!'

Upvotes: 1

Related Questions