Updating Array Elements in CoffeeScript Loops

Notes on updating array elements in CoffeeScript loops.

CoffeeScript doesn’t use the JavaScript C-style for(;;) loops. When one wishes to conditionally modify the array that’s being iterated over, how one might go about it may not be obvious at first.

If I wish to update an array without otherwise disturbing it, the “obvious” answer will not work:

shouldUpdate = (colour) ->
    .... details ....

colours = ['red', 'green', 'blue']
for colour in colours
    colour = "foo" if shouldUpdate(colour)

This is because the compiler produces code like:

for (_i = 0, _len = colours.length; _i < _len; _i++) {
  colour = colours[_i];
  if (shouldUpdate(colour)) {
    colour = "foo";

Note that in line 2 the value in colours[_i] is copied to a separate variable colour, thus assigning to colour will not affect the array itself.

If we wish to modify the array in place, then we can tell CoffeeScript to provide us with the index thus:

shouldUpdate = (colour) ->
    .... details ....

colours = ['red', 'green', 'blue']
for colour, index in colours
    colours[index] = "foo" if shouldUpdate(colour)

There may be a slicker way to do this, but for now it suits my purposes.


This entry was posted in Programming and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Updating Array Elements in CoffeeScript Loops

  1. Corey says:


  2. Brent says:

    Useful for this Coffeescript novice, thanks for posting 🙂

Leave a Reply