How to use _.each(underscore js)
Table of contents
Underscore is a JavaScript library that provides several of the useful functional programming aids without extending any native objects. It provides a number of useful functions for programming, such as each map, filter, and invoke, without requiring the use of any built-in objects.
In this article, our focus will be on each from the underscore package.
The _.each() function is a JavaScript function that returns each element in a list. It basically iterates each item of an array or an object through a callback function.
Syntax
_.each(list, callback);
List:It is a list that contains some elements.
Callback: This is regarded as the function. It is executed by selecting an element from the list.
Ex.1
Getting the values in an array along with their index:
_.each(["fish","chicken","meat","turkey","console.log);
Output:
Here, we are getting our result from our console. We can see it displaying the values and the index.
We could also write it like this for better readability:
_.each(["1","2","3","4 "],function(index, value){
console.log('index=',index,'value=',value)
})
let's pass a context to it in the next example. A context simply means an object inside an object.
Ex2
const example = {
details:{
name: "john doe",
age:45,
color:"black"
}
}
_.each(['name','age','color'], function(val){
console.log(this)
},
example.details
)
we could also write like this:
const example = {
details:{
name: "john doe",
age:45,
color:"black"
}
}
_.each(['name','age','color'], function(val, key,object){
console.log(val,key,object)
}
)
If you’re looking for a clean code then using the underscore.js _.each is the right choice. It gives you clean, readable code takes precedence . Let’see how it compares with using foreach with an example
using the nativeforeach
const numbers = [1, 2, 3, 4, 5];
for (i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
for _.each:
_.each(numbers,function(index,value){
console.log(index,value);
})
When comparing both codes you’ll notice that the underscore js.tends to be more readable and understandable than the native foreach
Conclusion
we talked about the _.each(), its syntax as well as examples showing how to use it. We also compared it with the native foreach in javascript to see how it stands out in terms of readability. Ler me know your thoughts in the comment section.