Reputation: 1481
In my Javascript code, I process many json objects with properties that may be null:
if (store.departments != null) {
for(var i = 0; i < store.departments.length; i++) {
alert(department.name);
}
}
In porting my app to coffeescript, I came up with the following shortcut using the existential operator:
for department in store.departments ? []
alert department.name
Is this acceptable coffeescript? Is there any scenario in which this would not work as intended?
Upvotes: 2
Views: 2430
Reputation: 31
If I understand what your'e asking, this code doesn't do what you're thinking.
for department in store.departments ? []
It looks like you're using the existential operator ?
similar to how you would a ternary operator a?b:c
.
From coffeescript.org:
It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?
If I wanted to later use the names, I'd write something like:
if store.departments?
names = (department.name for department in store.departments)
You could put it all on one line, but with a list comprehension, that becomes pretty unreadable. The existential operator will test null && undef and only return true if it really exists.
If you want to use a ternary operator in coffeescript, it's less terse:
for department in if store.departments? then store.departments else []
Maybe not exactly what you want, because it's extraordinarily verbose here.
Upvotes: 1
Reputation: 22258
What about this?
if store.departments
alert department.name for department in store.departments
Or
alert department.name for department in store.departments if store.departments
Both statements compile to:
var department, _i, _len, _ref;
if (store.departments) {
_ref = store.departments;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
department = _ref[_i];
alert(department.name);
}
}
Upvotes: 2