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

Author: neptune | 02nd-Apr-2023
#JavaScript #React.js

What is a function?

In JavaScript, a function is a block of code that performs a specific task. It is a reusable piece of code that can be called multiple times with different inputs to produce different outputs. Functions are an essential part of JavaScript programming, and they help in making the code more organised, modular, and easy to maintain.

Why JavaScript?

JavaScript is a versatile programming language that can be used for both front-end and back-end development. It has a vast collection of built-in functions that can be used to perform various tasks. However, not all functions are created equal. Some functions are pure, while others are impure.

What is a pure function?

A pure function is a function that always returns the same output for the same input. It does not have any side effects, which means it does not modify any external state or variables. Pure functions are predictable, and they do not depend on any external factors. They only depend on their input parameters.

For example, consider the following pure function that adds two numbers:


function add(a, b) {

    return a + b;



This function will always return the same output for the same input. If we call add(2, 3), it will always return 5. It does not modify any external state or variables.

What is an impure function?

An impure function is a function that has side effects. It modifies external state or variables, and it may not always return the same output for the same input. Impure functions are unpredictable, and they depend on external factors.

For example, consider the following impure function that modifies an external variable:

 let count = 0;

 function increment() {



This function modifies the external variable count, and it does not return any value. If we call increment() multiple times, the value of count will keep increasing. This function has side effects and is impure.

Why are pure functions useful?

Pure functions have several advantages over impure functions. They are predictable, which makes them easier to test and debug. They do not have any side effects, which makes them safer to use in a multi-threaded environment.

Pure functions are useful because they have several advantages over impure functions:

1. Predictability: Pure functions always return the same output for a given input. This makes them predictable and easier to reason about.

2. Testability: Since pure functions don't have any side effects, they are easier to test. You can test them by passing in different inputs and verifying that the output is correct.

3. Reusability: Pure functions can be reused in different parts of your codebase without worrying about side effects. This makes them more modular and easier to maintain.

4. Parallelism: Pure functions can be executed in parallel without any synchronisation issues. This can lead to better performance in certain scenarios.

5. Refactoring: Pure functions are easier to refactor because they don't have any dependencies on external state. You can change the implementation of a pure function without worrying about breaking other parts of your codebase.

Overall, pure functions promote good programming practices and can lead to more maintainable and scalable code.

How to create pure functions in JavaScript?

To create a pure function in JavaScript, you need to ensure that it does not modify any external state or variables. It should only depend on its input parameters and return a value. You should also avoid using any global variables or functions inside the pure function.

Here are some guidelines for creating pure functions in JavaScript:

1. Avoid modifying external state: A pure function should not modify any external state, such as global variables or objects passed by reference. Instead, it should only use its input arguments to compute the output.

2. Avoid using random values: A pure function should not use any random values or generate any random output. This can make the function unpredictable and difficult to test.

3. Avoid using current time or date: A pure function should not use the current time or date as input or output. This can make the function unpredictable and difficult to test.

4. Avoid using console.log: A pure function should not use console.log or any other side-effecting functions. This can make the function difficult to test and debug.

5. Use immutable data structures: A pure function should use immutable data structures, such as arrays and objects that cannot be modified. This ensures that the function does not accidentally modify any external state.

6. Return a value: A pure function should always return a value. This makes it easier to compose functions and reason about their behaviour.

Pure vs Impure Functions

Pure functions are better than impure functions in most cases. They are easier to test, debug, and reason about. They are also safer to use in a multi-threaded environment. However, impure functions are sometimes necessary, especially when dealing with external resources like databases or network calls.

Inbuilt pure functions in JavaScript:

JavaScript has several built-in pure functions that you can use in your code. Some of the most commonly used pure functions are:

- Math.abs()

- Math.max()

- Math.min()

- Array.concat()

- Array.slice()

- Array.join()

Inbuilt impure functions in JavaScript:

JavaScript also has several built-in impure functions that you should be aware of. Some of the most commonly used impure functions are:

- Array.push()

- Array.pop()

- Array.shift()

- Array.unshift()

- Array.splice()



In conclusion, pure functions are an essential part of JavaScript programming. They are predictable, safe, and easy to reason about. You should try to use pure functions whenever possible and avoid using impure functions unless necessary. By following this approach, you can write cleaner, more maintainable, and bug-free code.

Related Blogs
Create Your First App in React with Redux | Counter app
Author: neptune | 30th-Mar-2023
Creating your first app in React can be a daunting task, but with the right guidance, it can be a fun and rewarding experience. Will guide you to create a counter app in React with redux...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

React: Slideshow App | Fresco Play Hackerrank
Author: neptune | 05th-Nov-2023
One interesting project that showcases these qualities is the Slideshow App, a simple yet impactful application that allows users to navigate through a collection of slides...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

React.js vs React Native ÔÇô What's the Difference?
Author: neptune | 26th-Mar-2023
React.js and React Native are both frameworks developed by Facebook for building user interfaces. However, they are not the same and have different use cases...

Essential Topics to Master React JS
Author: neptune | 21st-Feb-2024
A Comprehensive Guide to Components, State, JSX, Event Handling, Routing, Redux, Hooks, Testing, Performance Optimization, and Server-Side Rendering...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

Opportunities - React Django Developer
Author: neptune | 14th-Apr-2023
#React.js #Django
React Django stack is popular for building web applications. Opportunities for React Django developers in Full Stack, Web, and Software development roles...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Why React Refuses to Die ?
Author: neptune | 01st-Jun-2023
React's success stems from addressing UI development challenges, nurturing a vibrant ecosystem, and its demand in the job market. Challenges exist, but React continues to evolve and remain relevant...

Allow One Function Call | #2666 | LeetCode Solution
Author: neptune | 11th-Sep-2023
#JavaScript #LeetCode
Given a function `fn`, return a new function that is identical to the original function except that it ensures `fn` is called at most once...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

­čś▒ How React Kicks Off OOPs ? ­čś▒
Author: neptune | 01st-Jun-2023
React kicks off OOPs by replacing inheritance with composition, achieving code reuse and modularity while promoting functional programming...

Memoize | #2634 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value...

Components and Props: Understanding the Backbone of React Applications
Author: neptune | 23rd-Jul-2023
React is a popular JavaScript library for building user interfaces. One of the fundamental concepts in React is the use of components and props...

Functional vs Class Components in React: All you need to know?
Author: neptune | 21st-Apr-2023
React components are building blocks for UIs. They can be functional (stateless) or class (stateful). Components are called using their names as HTML tags...

Array Prototype Last | #2619 | LeetCode Solution
Author: neptune | 20th-Sep-2023
#JavaScript #LeetCode
Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element...

Celebrating 10 Years of React: A Decade of Innovation
Author: neptune | 01st-Jun-2023
React celebrates its 10th anniversary, revolutionizing frontend development with its innovative concepts, ecosystem growth, and impact on mobile development...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

6 Brilliant JavaScript Frameworks for Every Developer
Author: neptune | 16th-Feb-2024
JavaScript's web development with frameworks like Synaptic.js for neural networks, OpenCV.js for multimedia processing, D3.js for dynamic data visualizations, Compromise.js for efficient NLP, ConvNet...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

State in React: Component State and Controlling Behavior
Author: neptune | 21st-Feb-2024
#JavaScript #React.js
React, a popular JavaScript library for building user interfaces, introduces the concept of state and lifecycle methods to help developers manage the dynamic nature of components...

Decode Secret Language of React: Game-Changer for Web Developers
Author: neptune | 25th-Feb-2024
#JavaScript #React.js
JSX is a syntax extension for JavaScript recommended by React for describing what the UI should look like...

View More