Categories
interview

Looping through Arrays and Objects in Javascript

///  ARRAYS ///
const arr = [1, 2, 3];

for (const val of arr) {
  console.log(val);
}

for (const [key, val] of arr.entries()) {
  console.log(key, val);
}

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

///  OBJECTS ///

const obj = {
  abc: 123,
  cc: 33
};

for (const [key, val] of Object.entries(obj)) {
  console.log(key, val);
}

for (const [key] of Object.entries(obj)) {
  console.log(key);
}

for (let key in obj) { // returns Enumerable (peperties whose internal flag is set to true) properties as well.
  if (obj.hasOwnProperty()) {
    console.log(obj[key])
  }
}

Demo