What is Pure Function in JavaScript: Definition and Examples
pure function in JavaScript is a function that always returns the same output for the same input and does not cause any side effects like changing external data. It behaves like a reliable machine where the output depends only on the input values.How It Works
A pure function works like a simple vending machine: you put in a specific coin (input), and it always gives you the same snack (output) without changing anything else around it. It does not rely on or change any outside information, so it is easy to understand and trust.
Because pure functions don’t change external data or depend on anything outside their input, they are predictable and easy to test. This means if you call the function multiple times with the same input, you will always get the same result, just like pressing the same button on a vending machine always gives the same snack.
Example
This example shows a pure function that adds two numbers. It always returns the same result for the same inputs and does not change anything outside itself.
function add(a, b) { return a + b; } console.log(add(2, 3)); console.log(add(2, 3));
When to Use
Use pure functions when you want your code to be easy to understand, test, and debug. They are great for calculations, data transformations, and any logic that should not affect or depend on outside data.
For example, in a shopping app, calculating the total price from a list of items is a perfect use case for a pure function because it only depends on the input list and does not change anything else.
Key Points
- A pure function always returns the same output for the same input.
- It does not change or rely on anything outside its scope (no side effects).
- Pure functions are easier to test and debug.
- They help make code predictable and reliable.