Syntax, Parameter and Return Value
Syntax:
_.forEachRight(collection, [iteratee=_.identity])
Parameters:
-
collection (Array|Object): The collection to iterate over.
- [iteratee=_.identity] (Function): The function invoked per iteration.
Return Value:
Returns the original collection.
Examples
Reverse Iteration Over Array Elements:
JavaScript
var _ = require('lodash');
var numbers = [1, 2, 3];
_.forEachRight(numbers, value => console.log(value * 2));

You can also try this code with Online Javascript Compiler
Run Code
Output:
6, 4, 2
Demonstrates iterating over an array in reverse order.
Processing Object Properties in Reverse:
JavaScript
var user = { 'name': 'John', 'age': 30 };
var keys = Object.keys(user);
_.forEachRight(keys, key => console.log(key, user[key]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'age' 30, 'name' John
Shows reverse iteration over the properties of an object.
Breaking Out of the Loop:
JavaScript
_.forEachRight(numbers, (value) => {
if (value === 2) return false; // Breaks the loop
console.log(value);
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
3
Ilustrates stopping reverse iteration based on a condition.
Reverse Iteration Over a String:
JavaScript
var string = 'hello';
_.forEachRight(string, char => console.log(char.toUpperCase()));

You can also try this code with Online Javascript Compiler
Run Code
Output:
O, L, L, E, H
An example of iterating over each character of a string in reverse order.
Frequently Asked Questions
What are typical use cases for _.forEachRight()?
Typical use cases include processing data in reverse order, like traversing a stack, reverse searching in arrays, or implementing undo operations.
Can _.forEachRight() modify the original collection?
Similar to _.forEach(), if the iteratee function modifies the elements, those changes will reflect in the original collection.
Is there a performance difference between _.forEach() and _.forEachRight()?
Performance differences are generally negligible; the choice between them is based more on the required order of iteration.
Conclusion
Lodash's _.forEachRight() method is an effective solution for iterating over collections in reverse order. It provides the flexibility to handle scenarios where reverse processing is needed, enhancing the ability to manage data in various structures and formats.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.