JavaScript coding interview — Understand the looping/ iteration — Part 1

Arrays, Objects, and Strings are commonly used types that we iterate using ‘for’. ‘for…in’, ‘for…of’ statements.

Photo by Sean Alabaster on Unsplash
  1. for

Repeats until a specified condition evaluates to false.

for ([init]; [condition]; [increment])

“All the three blocks in the for loop can be omitted. But should be declared before.”

2. for…of

for (variable of iterable)

“Iterable can be ‘Array, String, array-like objects, TypedArray, Map, Set and user-defined iterables”.

Use the below code to test whether the object is iterable or not:

typeof obj[Symbol.iterator] === 'function'; // 'obj' will be the var

Don’t use loop for arrays. It iterates over both array indices and property keys. It will be ambiguous if someone adds a property to an array.

Built-in Iteration Methods

function(callback, [thisValue])//callback will be
function callBackFn(value, index, array)
  • forEach — calls a callback function once for each array element
Exclusive awesome reference on forEach:
  • every — check if all array values pass the test condition
Great examples here:
  • some — check if some array values pass the test condition


  • map — creates a new array; doesn't change the original array; doesn't execute the function without values
  • filter — creates a new array with elements that pass the test


  • reduce — runs a function on each array element to produce (or reduce it to) a single value; works from left-to-right; doesn't reduce the original array
arr.reduce(callback, initialValue);


  • reduceRight (same as reduce, but traverse from right-to-left)
  1. for…in — iterates over all enumerable properties of an object (excludes keyed by Symbols)
  2. Object.keys() — returns an array of a given object’s own enumerable property names, iterated in the same order.
  3. Object.entries() — returns an array of a given object’s own enumerable string-keyed property [key, value] pairs

important difference is that a loop enumerates properties in the prototype chain as well

  1. for — traditional approach
  2. for…of (ES6) — more convenient; no need to care about the current index
  3. forEach —preferred for functional programming; leverages immutability; higher-order function



Senior User Interface Engineer at Aruba Networks