how to use the foreach function from the underscore library in javascript

To use the each function from the Underscore library in JavaScript, you first need to include the library in your HTML file using a script tag.

<script src="https://underscorejs.org/underscore-min.js"></script>
67 chars
2 lines

Next, you can use the _.each function to iterate over an array and perform some action on each element.

index.tsx
const myArray = [1, 2, 3, 4, 5];

_.each(myArray, function(num) {
  console.log(num * 2);
});
94 chars
6 lines

In this example, the each function takes two arguments: the array to iterate over, and a function to perform on each element. The function takes one argument (in this case, num) that represents the current element of the array, and performs some action (in this case, logging num * 2 to the console).

The each function can also be used with objects, in which case the function will be passed two arguments: the value of each property and the name of each property.

index.tsx
const myObject = {a: 1, b: 2, c: 3};

_.each(myObject, function(value, key) {
  console.log(key + ': ' + value);
});
117 chars
6 lines

In this example, the each function is used to iterate over the properties of an object, and logs each property name and value to the console.

gistlibby LogSnag