I use the identity function in all my JavaScript programs:
function identity(value) {
return value;
}
The reason is that I often need differentiate between primitives types (undefined, null, boolean, number and string) and object types (object and function) as returned by the typeof operator. I feel using the indentity function for this use case very succuint:
if (new identity(value) == value); // value is of an object type
if (new identity(value) != value); // value is of a primitive type
The identity function is much smaller and simpler than the following code:
function isObject(value) {
var type = typeof value;
return type == "object" || type == "function";
}
However on reading my code a friend of mine complained that my hack is misleading and more computationally expensive than the above alternative.
I don't want to remove this function from any of my programs as I believe it's an elegant hack. Then again I don't write programs solely for myself. Is there any other use case for the identity function in JavaScript?
value === Object(value)? Or, for more readable code, defineisObjectto use it?var func = optionalProcessFunc || identityFunc;. Now later on in the code, you don't need to know anything about how this section was configured to run. More generally, if you want to treat functions as monoids, it's convenient to use the identity function as mzero and compose as mconcat.