Arrays, Objects, and Strings are commonly used types that we iterate using ‘for’. ‘for…in’, ‘for…of’ statements.
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.”
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 for..in 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
- 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
- reduceRight (same as reduce, but traverse from right-to-left)
- for…in — iterates over all enumerable properties of an object (excludes keyed by Symbols)
- Object.keys() — returns an array of a given object’s own enumerable property names, iterated in the same order.
- Object.entries() — returns an array of a given object’s own enumerable string-keyed property
important difference is that a
for...inloop enumerates properties in the prototype chain as well
- for — traditional approach
- for…of (ES6) — more convenient; no need to care about the current index
- forEach —preferred for functional programming; leverages immutability; higher-order function
Loops and iteration
Iterable objects is a generalization of arrays. That's a concept that allows us to make any object useable in a for..of…