Menu
Coddy logo textTech

Pure Functions

Lesson 3 of 14 in Coddy's Function Declarations in JavaScript course.

In JavaScript, a pure function is one that, given the same input, will always return the same output and does not produce any observable side effects. Pure functions does not alter any external state or interact with outside variables.

Pure functions are particularly useful in:
Data Transformation: Ideal for mapping, filtering, and reducing data.
State Management: Ensures state immutability, especially in frameworks like Redux.

Syntax of a Pure Function:

function add(a, b) {
	return a + b;
}

The above given, 'add' function is pure because it always produces the same result for the same inputs and doesn’t affect any external state.

Syntax of an Impure Function:

let counter = 0;
function increment() {
	return counter++;
}

This 'increment' function is impure because it modifies external variables or states, causing side effects.

Refactoring an impure function to a pure function:

let total = 0;

// Impure function 
function addToTotal(amount) {
    total += amount;
    return total;
}

// Refactoring an impure function to a pure function
// Pure function (creates a new total)
function addToTotal(total, amount) {
	return total + amount;
}

In above example, refactoring an impure function to a pure function ensures it returns a new object without modifying the original.

challenge icon

Challenge

Easy

You need to write JavaScript code to refactor the existing impure function into a pure function, name this function nextBirthday.

The function should get one argument, the age.

Try it yourself

let userAge = 24;

// Impure function 
function celebrateBirthday() {
    userAge += 1;
    return userAge; 
} 
// Do not alter above code
// Write code here

All lessons in Function Declarations in JavaScript