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() {

  count++;

 }



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()

- Date.now()


Conclusion

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
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

React: Slideshow App | Fresco Play Hackerrank
Author: neptune | 05th-Nov-2023
#React.js
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...

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...

Create Your First App in React with Redux | Counter app
Author: neptune | 30th-Mar-2023
#React.js
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...

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...

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...

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...

React.js vs React Native – What's the Difference?
Author: neptune | 26th-Mar-2023
#React.js
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
#React.js
A Comprehensive Guide to Components, State, JSX, Event Handling, Routing, Redux, Hooks, Testing, Performance Optimization, and Server-Side Rendering...

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

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()...

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...

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...

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...

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...

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...

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...

Why React Refuses to Die ?
Author: neptune | 01st-Jun-2023
#React.js
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...

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

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

Celebrating 10 Years of React: A Decade of Innovation
Author: neptune | 01st-Jun-2023
#React.js
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
#JavaScript
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...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 31st-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

View More