This function is provided by AngularJs which returns the first argument provided. It is not available in later Angular versions (2,3,4….). It helps writing the code in a functional style. To understand it better let’s first take a brief look at what function style coding is.
Functional programming style is a programming paradigm where programs are constructed by applying and composing functions. This is achieved by avoiding using flow-control statements (for, while, break, continue, goto) which make the code harder to follow. Also, functional programming requires us to write pure, deterministic functions which are less likely to be buggy.
Using functional style in languages that support it can help reduce your code’s complexity. Functional programming adds the benefit of greater efficiency. It focuses on “what to do” rather than the “how to do”. Whereas Imperative programming focuses on “how to do”.
Lets see an example to better understand the use case of the identity function provided by AngularJs.
Let’s assume there is a transformer function which takes two arguments.
We want to return the original value if the transformationFn is not provided.
This is how we will write the function in a Imperative way.
function transformer(transformationFn, value) { if(transformerFn){ return transformerFn(value) } else { return value; } }; transformer(function(n) { return n * 2; }, 21); // returns 42 transformer(null, 21); // returns 21
The above code can be written in a functional manner by removing the multiple return statements and control flow statements. We can achieve this by the identity function provided by AngularJs.
function transformer(transformationFn, value) { return (transformationFn || angular.identity)(value) }; transformer(function(n) { return n * 2; }, 21); // returns 42 transformer(null, 21); // returns 21
The angular.identity function returns the first argument passed to it. So whenever transformationFn is not passed to the transformer function, we will return angular.identity(value), which in turn will return the value itself.