What language constructions do you use for iterating over object properties and array items?
Quiz · JavaScript
Medium
4 min
javascript
For objects:
for-inloops -for (var property in obj) { console.log(property); }. However, this will also iterate through its inherited properties, and you will add anobj.hasOwnProperty(property)check before using it.Object.keys()-Object.keys(obj).forEach(function (property) { ... }).Object.keys()is a static method that will lists all enumerable properties of the object that you pass it.Object.getOwnPropertyNames()-Object.getOwnPropertyNames(obj).forEach(function (property) { ... }).Object.getOwnPropertyNames()is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it.
For arrays:
forloops -for (var i = 0; i < arr.length; i++). The common pitfall here is thatvaris in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introducesletwhich has block scope and it is recommended to use that instead. So this becomes:for (let i = 0; i < arr.length; i++).forEach-arr.forEach(function (el, index) { ... }). This construct can be more convenient at times because you do not have to use theindexif all you need is the array elements. There are also theeveryandsomemethods which will allow you to terminate the iteration early.for-ofloops -for (let elem of arr) { ... }. ES6 introduces a new loop, thefor-ofloop, that allows you to loop over objects that conform to the iterable protocol such asString,Array,Map,Set, etc. It combines the advantages of theforloop and theforEach()method. The advantage of theforloop is that you can break from it, and the advantage offorEach()is that it is more concise than theforloop because you don't need a counter variable. With thefor-ofloop, you get both the ability to break from a loop and a more concise syntax.
Most of the time, I would prefer the .forEach method, but it really depends on what you are trying to do. Before ES6, we used for loops when we needed to prematurely terminate the loop using break. But now with ES6, we can do that with for-of loops. I would use for loops when I need even more flexibility, such as incrementing the iterator more than once per loop.
Also, when using the for-of loop, if you need to access both the index and value of each array element, you can do so with the ES6 Array entries() method and destructuring:
const arr = ['a', 'b', 'c'];
for (let [index, elem] of arr.entries()) {
console.log(index, ': ', elem);
}
Adapted from the Front End Interview Handbook by Yangshun Tay and contributors (MIT License). Source
Spotted a mistake or a rights concern? Report an issue