Better loops in JavaScript
Tags: javascript, node, web, programming
Published: 2018-12-16 13:52:37

---
title: Better loops in JavaScript
published: true
description: In this post, we will take a look at forms of for loop, array methods using which you can make your code simpler, more readable. These loops / methods are useful when you want to manipulate data in an array or object.
tags: js, node, web, programming
---



![Loops](https://thepracticaldev.s3.amazonaws.com/i/cgygkj9geu9zxxel8n98.jpg)


In this post, we will take a look at forms of for loop, array methods using which you can make your code simpler, more readable. These loops / methods are useful when you want to manipulate data in an array or object.

### for in loop

With this kind of loop you don't have to iterate over array indices, object keys manually.

```js
//iterating over an array
let arr = [1, 2, 3, 4, 5]
for (let index in arr) {
  console.log(arr[index])
}
// Output: 1,2,3,4,5

//iterating over object keys
let obj = { id: 1, msg: 'hello' }
for (let key in obj) {
  console.log(obj[key])
}
// Output: 1, hello
```

### for of loop

Using this loop you can get the value at a particular index. This loop only works on arrays.

```js
for (let val of arr) {
  console.log(val)
}
// Output: 1,2,3,4,5
```

## Array methods

Now let's take a look at a few array loop methods. When processing arrays the loops tend to become too large, we have to explicitly push items into another array and so on. The following methods make it easier to deal with such scenarios. The following methods take a callback function as an argument that will be executed for each element in the array. Let's look at a few examples.

### Iterating over an array

For this, you can use the [array.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method. For-each takes a callback as an argument and executes it for each array element.

```js
// display index and value
arr.forEach((value, index) => console.log(`Index = ${index} Value = ${value}`))
```

### Transforming an array

To transform an existing array into another form you can use [array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method. The map() method takes a callback as an arguement and returns a new array. The elements in the new array will be values that were returned by the callback.

Let's say you have an array of objects, each object has id, name. You want an array that contains just the ids.

#### with for loop

```js
let data = [
  { id: 1, name: 'Phone', type: 'electronic' },
  { id: 2, name: 'Laptop', type: 'electronic' },
  { id: 3, name: 'Shirt', type: 'clothing' },
]
let ids = []
for (let i = 0; i < data.length; i++) {
  ids.push(data[i].id)
}
```

#### with map

```js
let ids = data.map(function(val) {
  return val.id
})
```

#### or even shorter and simpler with an arrow function

```js
let ids = data.map(val => val.id)
```

### Filtering elements from the array

To filter elements from the array you can make use of [array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method. The filter() method expects a callback, this callback will be executed for each element in the array & returns a new array that contains filtered items. If the callback function returns true for a given element that element will be in the filtered array.

#### Selecting electronic items

```js
let electronics = data.filter(item => item.type == 'electronic')
```

### Searching for an element in the array

If you want to search for an element in the array you can use [array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method. Like all the other methods discussed here, this method also requires a callback. The callback function should return true or false. The the first value for which the callback returns true will be the output of this method. If there is no match, the function will return undefined.

#### Searching for name 'Phone'

```js
data.find(val => val.name == 'Phone')
```

### Getting a single value from an array

To obtain a single value from an array you can use the [array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method. The reduce() method, takes a callback function, initial value as an argument. The callback intern has an accumulator, currentValue as mandatory arguments. Accumulator contains the value that was obtained from the previous execution of the callback, currentValue is the array element under processing.

#### Sum and product of the array

```js
let arr = [1, 2, 3, 4, 5]

//sum of array elements
arr.reduce((accumulator, currentValue) => (accumulator + currentValue), 0)
// where 0 is the initial value
// Output: 15

// product of array elements
arr.reduce((accumulator, currentValue) => (acc * currentValue), 1)
// Output: 120
```

### Checking if a condition is true for at least one element in the array.

For this use [array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) method. This method will return true if the condition is true on at least one element in the array, otherwise it will return false.

```js
let friends = [13, 15, 16, 18] //ages of group of friends

// checking if at least one of them is 18 or above
friends.some(val => val >= 18)
```

### Checking if a condition is true for all the elements in the array

For this use [array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) method. This method will return true if a condition is true for all the elements in the array, otherwise it will return false.

```js
let giftPrices = [300, 350, 399, 400]
let budgetPerGift = 450

let checkBudget = price => price <= budgetPerGift

giftPrices.every(checkBudget) // true

budgetPerGift = 300

giftPrices.every(checkBudget) // false
```


### Things to take care of
- The array methods are slightly slower than normal [for loop](https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7), but they offer a lot of advantages, and their performance will improve with changes to JS engines.
- All the methods that we have discussed above (except some(), find()), execute on the entire array. If you don't want to do this than these methods are of no use to you. You can't use break to stop the callback.


That's it for today. These methods have lot's of potential, go through their documentation on MDN, try these out.

If you like this post do share it :).