How to iterate over the keys and values in an object in CoffeeScript?

Use for x,y of L. Relevant documentation.

ages = {}
ages["jim"] = 12
ages["john"] = 7

for k,v of ages
  console.log k + " is " + v

Outputs

jim is 12
john is 7

You may also want to consider the variant for own k,v of ages as mentioned by Aaron Dufour in the comments. This adds a check to exclude properties inherited from the prototype, which is probably not an issue in this example but may be if you are building on top of other stuff.


You're initializing an array, but then you're using it like an object (there is no "associative array" in js).

Use the syntax for iterating over objects (something like):

for key, val of arr
  console.log key + ': ' + val 

The short hand version using array comprehension, which can be used as a one-line loop.

console.log index + ": " + elm for index, elm of array

Array comprehension are:

"Comprehensions replace (and compile into) for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.", http://coffeescript.org/#loops