Better loops in JavaScript

Better loops in JavaScript

<strong>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.</strong>

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.

//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.

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() method. For-each takes a callback as an argument and executes it for each array element.

// 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() 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

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

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

or even shorter and simpler with an arrow function

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() 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

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() 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’

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() 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

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() method. This method will return true if the condition is true on at least one element in the array, otherwise it will return false.

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() method. This method will return true if a condition is true for all the elements in the array, otherwise it will return false.

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, 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 :).

Originally published by Kartik Malik at https://dev.to

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ Vue.js Authentication System with Node.js Backend

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.