What is a utility function?

Definition

You may have heard the term utility function before but you may not understand exactly what a utility function is. A utility function is a function that has certain properties:

1) A utility function must not have side effects. A side effect in a function is any programming operation that accesses or modifies any state. A side effect might include:

  • logging to the console
  • changing the value of some variable
  • writing some data to the disk
  • dynamically adding a new element to the DOM

Basically: side effect = changing something somewhere.

let num = 2;

// wrong
function notUtilityFunction(x)
{
	console.log("hello, this is a side effect"); // side effect
	num = 4; // side effect
	localStorage.setItem("num", num); // side effect
}

// correct
function utilityFunction(x)
{
	return Math.pow(x,3); // not manipulating any state
}

2) A utility function’s output must depend directly on it’s input. A utility function usually takes in some value A and returns some value B (without changing A in the process)! B must directly depend on what A is and B must not rely on any random factors or operations that could produce a different result the next time the function is ran. For every A that is passed in to a utility function, there is exactly one B.

// wrong
function notUtilityFunction(A)
{
    return A * Math.random() * 3; // Result is not directly dependent on 'A'.
    // Return value will change depending on the random number that is generated
}
notUtilityFunction(3); // ? result depends on Math.random()


// correct
function utilityFunction(A)
{
    return A * 3; // Result is directly dependent on 'A'.
    // No matter what A you pass in, the same value will be returned (A*3)
}

utilityFunction(9); // ALWAYS 27

Summary

A utility function is a standalone function that does not have any side effects and whose output is directly dependent on it’s input. Utility functions perform common and often reused routines.

If this article was helpful, tweet it!