My learning diary

for-in and for-of

I needed to change my async code into synchronous. I didn’t need to track the index of the array, so I wanted a for...?? loop.

Was it for...in or was it for...of!?

for...in

Example: for (let key in someObject)

const a = [4,5,6]
const b = [{'k1':'v1'},{'k2':'v2'},{'k3':'v3'}]
const c = {'k1':'v1'}

for (let d in a) { console.log(d) } // 0 1 2
for (let d in b) { console.log(d) } // 0 1 2
for (let d in c) { console.log(d) } // k1

for...of

Example: for (let value of someIterable)

const a = [4,5,6]
const b = [{'k1':'v1'},{'k2':'v2'},{'k3':'v3'}]
const c = {'k1':'v1'}

for (let d of a) { console.log(d) } // 4 5 6
for (let d of b) { console.log(d) } // {'k1':'v1'} {'k2':'v2'} {'k3':'v3'}
for (let d of c) { console.log(d) } // Uncaught TypeError: c is not iterable

Relevant posts