Map the Debris: "for ... in" or "for" loops is better?

Maybe its better to show it on display

const arr=['one', 'two', 'three']

for (let index in arr) {
  console.log(index)  //0, 1, 2
  console.log(arr[index]) //one, two, three
}

for (let item of arr) {
  console.log(item)  //one, two, three
}

let lastIndex=arr.length-1  // 2
for (let i=lastIndex; i>=0; i-=2) {
  console.log(i) //2, 0
  console.log(arr[i]) //three, one
}

const obj={
  a: 'alhpa',
  b: 'beta',
  c: 'gamma'
}

for (let key in obj) {
  console.log(key) //a, b, c
  console.log(obj[key])  //alhpa, beta, gamma
}

array
for...in- i loop throught the array indices(can access items via them)
for...of- i loop throught the array items(no access to indices)
for- can create advanced loop logic; in the example code i went throught the array indices in reverse order, while also skipping every other.

object
for...in- simple access to object properties(respectively their values)

1 Like