front-end-interview-handbook/packages/quiz/questions/what-language-constructs-do.../en-US.mdx

104 lines
4.6 KiB
Plaintext

---
title: What language constructions do you use for iterating over object properties and array items?
---
## Objects
### `for...in` statement
```js
for (const property in obj) {
console.log(property);
}
```
The `for...in` statement iterates over all the object's **enumerable** properties (including inherited enumerable properties). Hence most of the time you should check whether the property exists on directly on the object via `Object.hasOwn(object, property)` before using it.
```js
for (const property in obj) {
if (Object.hasOwn(obj, property)) {
console.log(property);
}
}
```
Note that `obj.hasOwnProperty()` is not recommended because it doesn't work for objects created using `Object.create(null)`. It is recommended to use [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) in newer browsers, or use the good old `Object.prototype.hasOwnProperty.call(object, key)`.
### `Object.keys()`
```js
Object.keys(obj).forEach((property) => {
console.log(property);
});
```
`Object.keys()` is a static method that will return an array of all the enumerable property names of the object that you pass it. Since `Object.keys()` returns an array, you can also use the array iteration approaches listed below to iterate through it.
_Reference: [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_
### `Object.getOwnPropertyNames()`
```js
Object.getOwnPropertyNames(obj).forEach((property) => {
console.log(property);
});
```
`Object.getOwnPropertyNames()` is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it. Since `Object.getOwnPropertyNames()` returns an array, you can also use the array iteration approaches listed below to iterate through it.
_Reference: [Object.getOwnPropertyNames() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)_
## Arrays
### `for` loop
```js
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
A common pitfall here is that `var` is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces `let` which has block scope and it is recommended to use `let` over `var`.
```js
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
### `Array.prototype.forEach()`
```js
arr.forEach((element, index) => {
console.log(element, index);
});
```
The `Array.prototype.forEach()` method can be more convenient at times if you do not need to use the `index` and all you need is the individual array elements. However, the downside is that you cannot stop the iteration halfway and the provided function will be executed on the elements once. A `for` loop or `for...of` statement is more relevant if you need finer control over the iteration.
_Reference: [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)_
### `for...of` statement
```js
for (let element of arr) {
console.log(element);
}
```
ES2015 introduces a new way to iterate, the `for-of` loop, that allows you to loop over objects that conform to the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) such as `String`, `Array`, `Map`, `Set`, etc. It combines the advantages of the `for` loop and the `forEach()` method. The advantage of the `for` loop is that you can break from it, and the advantage of `forEach()` is that it is more concise than the `for` loop because you don't need a counter variable. With the `for...of` statement, you get both the ability to break from a loop and a more concise syntax.
Most of the time, prefer the `.forEach` method, but it really depends on what you are trying to do. Before ES2015, we used `for` loops when we needed to prematurely terminate the loop using `break`. But now with ES2015, we can do that with `for...of` statement. Use `for` loops when you need more flexibility, such as incrementing the iterator more than once per loop.
Also, when using the `for...of` statement, if you need to access both the index and value of each array element, you can do so with ES2015 `Array.prototype.entries()` method:
```js
const arr = ['a', 'b', 'c'];
for (let [index, elem] of arr.entries()) {
console.log(index, ': ', elem);
}
```
_Reference: [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)_