Practical usage of identity function

Rohit Kumar

By Rohit Kumar

on March 20, 2018

If you are learning functional programming then you can't go far without running into "identity function".

An identity function is a very basic function that

  • takes one argument
  • returns the argument
1f(x) = x;

This seems like the most useless function in the world. We never needed any function like this while building any application. Then what's the big deal about this identity function.

In this blog we will see how this identity concept is used in the real world.

For the implementation we will be using Ramda.js. We previously wrote about how we, at BigBinary, write JavaScript code using Ramda.js.

Again please note that in the following code R stands for Ramda and not for programming language R.

Example 1

Here is JavaScript code.

1if (x) return x;
2return [];

Here is same code using Ramda.js.

1R.ifElse(R.isNil, () => [], R.identity);

try it

Example 2

Here we will use identity as the return value in the default case.

1R.cond([
2  [R.equals(0), R.always("0")],
3  [R.equals(10), R.always("10")],
4  [R.T, R.identity],
5]);

try it

Example 3

Get the unique items from the list.

1R.uniqBy(R.identity, [1, 1, 2]);

try it

Example 4

Count occurrences of items in the list.

1R.countBy(R.identity, ["a", "a", "b", "c", "c", "c"]);

try it

Example 5

Begin value from zero all the way to n-1.

1R.times(R.identity, 5);

try it

Example 6

Filter truthy values.

1R.filter(R.identity, [
2  { a: 1 },
3  false,
4  { b: 2 },
5  true,
6  "",
7  undefined,
8  null,
9  0,
10  {},
11  1,
12]);

try it

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.