Please explain usage of _.identity(value)
of underscore.js. Not able to understand it from the documentation ( http://underscorejs.org/#identity ).
Can you provide some example of its usage?
Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.
The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...
As discussed before, the identity describes the property of objects that distinguishes them from other objects. So, the reference identity is nothing more than the use of the object reference as identity. Variables that are assigned a non-primitive value are given a reference to that value.
The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.
A JavaScript code pattern involving identity is filtering values based on truthiness, e.g.
var a = [null, null, [1,2,3], null, [10, 12], null]; a.filter(_.identity)
yields [Array[3], Array[2]].
Using
_.compact(a)
is clearer, but one may not use lodash or underscore at all, e.g.
function identity(x) { return x; } a.filter(identity)
Whether it is a good code pattern is questionable for several reasons, but it's being used in the wild.
It is not a NOOP at all. A NOOP is an imperative construct in e.g. assembly, whereas in functional programming, it is like other functions in that it returns a value. If identity were a NOOP, then all pure functions could also be considered noop, and it would not be a sensible thing.
It's essentially a no-operation function. It returns the value of whatever was passed into it.
The part about it being used as a "default iterator" within the library itself means that in other functions which may have an optional "iterator" parameter (which is likely used as a function to apply to each element of an array of some kind), if no iterator parameter is passed, the library will use this "no-op" iterator instead and the elements of the array will remain unchanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With