Search code examples
coffeescript

When to use "from", "of" or "in" in coffeescript for-loops


I find the documentation very confusing. When should I use for x of y, for x from y and for x in y and what does it translate to in normal Javascript? What options are there?


Solution

  • # Coffeescript                       # Translates to Javascript
    
    # Iterables like Arrays and Generators:
    for e from arr                       # for (e of arr)
    
    # Arrays: "Comprehension"
    for e in arr                         # for (j = 0, len = arr.length; j < len; j++) {
    
    # Arrays, functionally:
    arr.forEach (a) =>                   # arr.forEach(a =>
    
    # Objects: "Comprehension"
    for k,v of obj                       # for (k in obj) {
                                         #   v = obj[k]
    
    # Objects, only where hasOwnProperty
    for own k,v of obj                   # for (k in obj) {
                                         #   if obj.hasProperty(k)
    # Or manually, where hasOwnProperty
    for [k,v] from Object.entries(obj)   # for (x of obj) {
                                         #   [k, v] = x;
    # Or manually, functionally, where hasOwnProperty
    Object.entries(obj)                  # Object.entries(obj)
      .forEach ([k,v]) =>                #   .forEach(([k, v]) =>
    
    # As embedded Javascript
    `for (e of arr)`                     # for (e of arr)
    `for (k in obj)`                     # for (k in obj)
    

    In short:

    • from becomes of
    • in becomes a sophicsticated for(;;)-loop and
    • of becomes in.