Pure Functions

Akash ThoriyaAkash Thoriya
1 min read

Expert-Level Explanation

A pure function in JavaScript is a specific kind of function that always produces the same output given the same input and does not cause any observable side effects like modifying global objects or state.

Creative Explanation

Imagine a pure function as a vending machine. For the same selection (input), it always gives you the same snack (output), and it doesn't change anything else around it (no side effects).

Practical Explanation with Code

// Pure function
function add(a, b) {
  return a + b; // Always returns the same output for the same inputs
}

console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5, same output as before

Real-world Example

A pure function is like a mathematical equation, e.g.,y = 2x + 3. For the same value of x, you always get the same y, and the equation does not interact with the world outside itself.

0
Subscribe to my newsletter

Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akash Thoriya
Akash Thoriya

As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.