Syntax, Parameter and Return Value
Syntax:
_.identity(value)
Parameters:
value: The value to return.
Return Value:
Returns the given value.
Examples
As a Default Function in Higher-Order Operations:
JavaScript
var _ = require('lodash');
var array = [1, 2, 3];
var result = _.map(array, _.identity);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
Demonstrates using _.identity() as a default iteratee in a map operation.
Using in Functional Compositions:
JavaScript
var double = n => n * 2;
var triple = n => n * 3;
var compose = _.flow([double, _.identity, triple]);
console.log(compose(2));

You can also try this code with Online Javascript Compiler
Run Code
Output:
12 (2 * 2 * 3)
Shows using _.identity() as a no-operation function in a functional composition.
As a Default Callback:
function fetchData(callback) {
callback = callback || _.identity;
// Fetch data and return it through the callback
callback('data');
}
fetchData();

You can also try this code with Online Javascript Compiler
Run Code
// Doesn't throw an error, silently ignores the lack of callback
An example of using _.identity() as a default callback in a function.
Filtering with Identity Function:
JavaScript
var mixedArray = [0, 1, false, 2, '', 3];
var compactArray = _.filter(mixedArray, _.identity);
console.log(compactArray);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
Demonstrates using _.identity() to filter truthy values from an array.
Frequently Asked Questions
Is _.identity() just a redundant wrapper around a variable?
While it might seem redundant, _.identity() is useful in functional programming paradigms, especially in places where a function is expected rather than a direct value.
Can _.identity() be used with multiple arguments?
_.identity() only returns its first argument. Any additional arguments passed to it will be ignored.
How does _.identity() benefit readability and maintainability?
Using _.identity() can make it clear to future readers of the code that a function intentionally does not transform its input, improving code readability and intent.
Conclusion
Lodash's _.identity() method is a simple yet powerful tool in functional programming, providing a straightforward way to pass values through a series of operations unaltered. It's especially useful in creating clear and concise code in scenarios that involve functional compositions, callbacks, and default operations.
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.