Last Updated: September 15, 2020
·
13.3K
· pmaoui

CoffeeScript : iterate anywhere (for...in, for...of) !

Here is a small summary of some useful iterations in Coffeescript

Arrays

Associative array :

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

for key, value of ages
    console.log key + " is " + value

Indexed array :

arr = ["a","b","c"]

for value in arr
    console.log "value without the key is :" + value

for value, key in arr
    console.log key + " is " + value

Objects

yearsOld = john: 10, bob: 9, lisa: 11

for child, age of yearsOld
    console.log child + ' has ' + age + ' year old'

To avoid properties inherited by the prototype :

for own child, age of yearsOld
    console.log child + ' has ' + age + ' year old'

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside