Advanced Topic 48 of 54 Programming Fundamentals
Pure Functions
Functions whose output depends only on inputs and cause no side effects.
How it works
A pure function always returns the same output for the same input and does nothing else: no I/O, no mutation of arguments or globals, no randomness or clock reads. This property, called referential transparency, means a call can be replaced by its result. Pure functions are easy to test, cache, reorder and run in parallel.
Step-by-step walkthrough
- Calling f(3) twice with the same input.
- always returns the same output.
- It does not read or change global state, files or the network.
- This makes it easy to test, cache and run in parallel.
- Printing or random numbers make a function impure.
Where it is used
Math helpers, formatters, validators, reducers in state-management libraries and business rules are best written as pure functions. Pushing impurity to the outer layer, with a pure core and thin imperative shell, is a widely used architecture.
Common pitfall
Hidden dependencies such as the current time, environment variables, global state or random numbers make a function impure without looking like it. Mutating an input argument is a subtle side effect. Pass such dependencies in as parameters so the function stays testable.
Where it fits in the course
Pure Functions is topic 48 of 54 in Programming Fundamentals, rated Advanced. It follows Functional Programming. The next topic is Immutability in Practice.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Pure Functions?
Where do people use Pure Functions?
What is the most common mistake with Pure Functions?
What should I learn before this topic?
How can I practice it?
Is Pure Functions hard to learn?
How long does it take to learn Pure Functions?
Which topics are related to Pure Functions?
What should I study after Pure Functions?
Related topics
- Functional Programming (Programming Fundamentals)
- Immutability in Practice (Programming Fundamentals)
- Composition over Inheritance (Programming Fundamentals)
- Currying and Partial Application (Programming Fundamentals)
- Functions and Relations (Theory & Discrete Math)
- Functions and Graphs (Math for Computing)
- Aggregate Functions (Databases)