You Need to Know About Pure Functions & Impure Functions in JavaScript

Code of Relevancy - Mar 28 '23 - - Dev Community

With this article, we will explore what pure/impure functions are and their differences in JavaScript. Let's dive in..


What is a function?

In the ocean of JavaScript, functions are an essential building block for creating complex and interactive apps.

One of the most common uses of functions is mapping, where they take input values and produce corresponding output values. This allows for the transformation and manipulation of data, which is critical in creating dynamic user experiences.


What is a pure function?

A pure function is a function where the return value is only determined by its arguments without any side effects. Let's say, if you call a function with the same arguments n number of times and n number of places in the application then it will always return the same value. Pure functions do not modify any external state, such as variables or objects outside the function. They only use the input arguments to perform calculations and return the result.

What is a pure function

To show you what I mean..

Below function takes two numbers, a and b, as input arguments and returns their sum. This function is a pure function because it always produces the same output for the same input and does not have any side effects.

function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Pure Functions


What is an impure function?

An impure function is a type of function, given the same input, may produce different output at different times. This is because impure functions can rely on external factors such as changes in global variables or other functions, that affect their behavior and output.

What is an impure function

Below function modifies the external variable counter by increasing its value by one each time it is called. This means that it has side effects and is not a pure function.

let counter = 0;

function increment() {
  counter++;
  return counter;
}
Enter fullscreen mode Exit fullscreen mode

Impure Functions


Why are pure functions useful?

Pure functions have several advantages over impure functions:

1) Predictability
Because pure functions always produce the same output for a given input, they are predictable and easy to reason about. Its easier to test and debug and reduces the likelihood of unexpected behavior in your code.

2) Reusability
Pure functions are modular and self contained, meaning that they can be reused in different parts of your codebase without affecting other parts. This can save time and reduce the amount of code you need to write.

3) Parallelization
Because pure functions do not modify external state, they can be executed in parallel without worrying about race conditions or other synchronization issues. This can lead to faster and more efficient code.


How to create pure functions in JavaScript?

1) Use only input arguments
Pure functions should use only their input arguments to perform calculations and return the result. They should not modify any external state or rely on external variables.

2) Avoid side effects
Pure functions should not have any side effects, such as modifying external variables or objects. They should only return a value based on the input arguments.

3) Avoid global state
Pure functions should avoid using global state, such as global variables or objects. This can make your code less predictable and harder to debug.

4) Return a value
Pure functions should always return a value based on the input arguments. They should not rely on external variables or objects to produce their output.


Pure vs Impure Functions

Pure vs Impure Functions in JavaScript


Inbuilt pure functions in JavaScript:

Math.abs(): Returns the absolute value of a number.

Math.ceil(): Returns the smallest integer greater than or equal to a given number.

Math.floor(): Returns the largest integer less than or equal to a given number.

Math.max(): Returns the maximum value from a set of numbers.

Math.min(): Returns the minimum value from a set of numbers.

Math.round(): Returns the nearest integer to a given number.

Math.sqrt(): Returns the square root of a given number.

parseInt(): Converts a string to an integer.

parseFloat(): Converts a string to a floating point number.

JSON.parse(): Converts a JSON string to a JavaScript object.

Array.prototype.concat(): Returns a new array that contains the elements of the original array plus any additional elements that were passed in as arguments.

Array.prototype.slice(): Returns a new array that contains a portion of the original array, specified by a start and end index.

Array.prototype.map(): Returns a new array that is the result of calling a provided function on each element of the original array.

Array.prototype.filter(): Returns a new array that contains only the elements of the original array that satisfy a provided testing function.

Array.prototype.reduce(): Returns a single value that is the result of applying a provided function to each element of the array.

String.prototype.toUpperCase(): Returns a new string that contains the original string in all uppercase letters.

String.prototype.toLowerCase(): Returns a new string that contains the original string in all lowercase letters.


Inbuilt impure functions in JavaScript:

Math.random(): Returns a random number between 0 and 1. This function relies on external state which is the current state of the random number generator and its output changes every time it is called.

Date.now(): Returns the current timestamp which is the number of milliseconds that have elapsed since January 1, 1970. This function relies on external state which is the current time and its output changes every time it is called.

console.log(): Writes a message to the console. It does not return a value but it has a side effect of logging information to the console.

setTimeout(): Executes a function after a specified delay which is specified in milliseconds. This function has a side effect of scheduling a function to be executed in the future.

setInterval(): Executes a function at a specified interval which is specified in milliseconds. This function has a side effect of scheduling a function to be executed repeatedly at a fixed interval.

document.write(): Writes HTML content to the document. It does not return a value but it has a side effect of modifying the document.

Math.floor(Math.random() * (max - min + 1) + min): Returns a random integer between a given range. This function relies on external state which is the current state of the random number generator and its output changes every time it is called.

Math.pow(): Returns the result of raising a number to a given power. While this function is mathematically pure, it may result in floating point rounding errors that can make its output impure.


❤ Motivation:

Do more


🍀Support

Please consider following and supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!

YouTube
Discord
GitHub

Dour Darcel #8740

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player