0

I have the following code that obviously works but I am fairly sure there is a more terse way of expressing this in coffeescript:

  todos = []

  for i in [1..10]                                                                            
    todos.push App.store.find App.Todo, i 

1 Answer 1

1
todos = (App.store.find(App.Todo, i) for i in [1..10])

The enclosing parentheses indicate a list comprehension, which collects the return values into an array and returns it.

Consider the two following examples. The enclosing parentheses change how Coffeescript interprets the loop.

# With parentheses (list comprehension)
todos = (App.store.find(App.Todo, i) for i in [1..10])

# Without parentheses (plain old loop)
todos = App.store.find(App.Todo, i) for i in [1..10]

And the output:

// With parentheses
todos = (function() {
  var _i, _results;
  _results = [];
  for (i = _i = 1; _i <= 10; i = ++_i) {
    _results.push(App.store.find(App.Todo, i));
  }
  return _results;
})();

// Without parentheses
for (i = _i = 1; _i <= 10; i = ++_i) {
  todos = App.store.find(App.Todo, i);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The parentheses alter what CoffeeScript considers the body of the loop to be, not whether or not it will evaluate to an array (consider what this loop compiles to). The loop won't be arrayified if the compiler detects that the array won't be used (as in this loop).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.