Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

underscore.js

What is the each function in UnderscoreJS?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In UnderscoreJS, the each() method iterates over a list of elements. This list could be an array or an object.

Syntax

The syntax for this is given in the following way:

_.each(list, callback)
The syntax for the each method in UnderscoreJS

Parameters

It takes the two following parameters:

  • list: This could be an array or an object.
  • callback: This is a callback function that will work on the iterated elements. If the list is an array, it can take three arguments: element, index, and array. Here, index and array are optional. If it is an object, it will take value, key, and object. Here, key and object are optional.

Return value

It returns the list or the elements of the object.

Code

Let's look at the following example to see how the each() method works:

// require underscore
const _ = require("underscore")
// create some lists: arrays and objects
let arr1 = [1, 2, 3, 4, 5]
let arr2 = ["a", "b", "c", "d"]
let obj1 = {one: 1, two: 2, three: 3, four: 4}
let obj2 = {name: "nodejs", package: "underscore", tag: "_"}
// using the each method
console.log("elements present in "+arr1+" are:")
_.each(arr1, (element)=>{
console.log(element)
})
console.log("elements and their index present in "+arr2+" are:")
_.each(arr2, (element, index)=>{
console.log(element, index)
})
console.log("values present in object "+JSON.stringify(obj1)+" are:")
_.each(obj1, (value)=>{
console.log(value)
})
console.log("values and their keys present in object "+JSON.stringify(obj2)+" are:")
_.each(obj2, (value, key)=>{
console.log(value, key)
})
Use the each method of UnderscoreJS

Explanation

  • Line 2: We require the underscore package.
  • Line 5–8: We create some lists in the form of arrays and objects.
  • Lines 12, 17, 22, and 27: We use the each() method to iterate the lists and print their elements to the console.

RELATED TAGS

underscore.js

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring