JavaScript vs. CoffeeScript for...in and for...of loops

I write in CofeeScript and new JavaScript (ES6) as well. I found myself stuck every time when I need to write a simple iteration throught an array or object. Why? Well, probably because the definition is totally opposite in these languages.
Here are notes and code examples to clear it up: 

 JavaScript (ES6)

The for–in loop is for looping over object properties. 
The for–of loop is for looping over data—like the values in an array.
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

CoffeeScript 

The for-in loop - array 
The for-of loop - object 

Taken from https://coderwall.com/p/jwqrwq/coffeescript-iterate-anywhere-for-in-for-of

//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'

Comments

Popular posts from this blog

Peggle game in Godot 3 > Tutorial 01 - Create a new project

Peggle game in Godot 3 > Tutorial 02 - Rotate cannon by mouse move

My Vocabulary App Privacy Policy