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.
Array iteration
- 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 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:
https://dmitripavlutin.com/foreach-iterate-array-javascript/
- every — check if all array values pass the test condition
Great examples here:https://scotch.io/glossary/javascript/array-every-methodhttps://medium.com/@JeffLombardJr/when-and-why-to-use-the-every-array-method-in-javascript-29ff42a40522
- some — check if some array values pass the test condition
Transform
- map — creates a new array; doesn't change the original array; doesn't execute the function without values
https://ultimatecourses.com/blog/array-map-javascript
- filter — creates a new array with elements that pass the test
Reduce
- 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);
Reference: https://www.digitalocean.com/community/tutorials/js-finally-understand-reduce
- reduceRight (same as reduce, but traverse from right-to-left)
Objects iteration
- 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
[key, value]
pairs
important difference is that a
for...in
loop enumerates properties in the prototype chain as well
Strings iteration
- 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