Logo
Logo
Home
Archive
AI Agent Notes
Advertise
YouTube
Login
Sign Up
Logo
  • Home
  • Posts
  • 🦥What Are Pure Functions?

🦥What Are Pure Functions?

Apr 24, 2025

Sponsored by

Hello friends!

Welcome to this week’s super late Sloth Bytes uh… I hope you had an amazing week.

Find out why 1M+ professionals read Superhuman AI daily.

AI won't take over the world. People who know how to use AI will.

Here's how to stay ahead with AI:

  1. Sign up for Superhuman AI. The AI newsletter read by 1M+ pros.

  2. Master AI tools, tutorials, and news in just 3 minutes a day.

  3. Become 10X more productive using AI.

Join 1 million pros and start learning AI

Pure Functions

So I’ve recently been studying a bit of functional programming because I wanted to see what was so good about it.

Functional bros really enjoy it (Haskell users…)

And one concept that really stood out to me is the idea of pure functions.

I’ve heard the term and a lot of people prefer writing functions like this and after reading about them, I definitely understand why.

It’s VERY simple and incredibly powerful.

It has a lot of benefits like reducing bugs, improving readability, and makes your code easier to test.

What Is a Pure Function?

Technical explanation:
A pure function’s result depends only on its explicit inputs, and evaluating it does not cause observable side effects outside the function. In practical programming terms, the same immutable input values should produce the same output value, and the function should not mutate shared state, write files, perform network I/O, change the DOM, log, etc.

Analogy:
It’s like a vending machine that always gives you the same snack for the same code. No matter how many times you press B2, you get chips. No surprises.

Example (JavaScript of course):

//Pure function: Same inputs, same outputs, no side effects.
function add(a, b) {
  return a + b;
}
//Impure: Relies on external state and modifies it
let counter = 0;
function impureAdd(a) {
  counter++;
  return a + counter;
}

Why Use Pure Functions?

  • Predictability: The output follows from the inputs instead of hidden mutable state, clocks, randomness, or external services.

  • Testability: Many pure functions can be tested by passing values in and asserting the value that comes out.

  • Debuggability: There are fewer hidden dependencies and side effects to reason about. Bugs can still exist in the function’s own logic, its callers, or bad input assumptions.

  • Composition: Small deterministic transformations are often easy to combine, memoize, parallelize, or reuse.

Pure functions are a central idea in functional programming and also show up constantly in ordinary JavaScript/TypeScript, reducers, data transformations, selectors, validation, calculations, and other code that benefits from explicit inputs and outputs.

What the heck are Side Effects?

A side effect is an observable interaction with state outside the function’s return value.

Examples include writing to a database/file, making a network call, mutating an object owned elsewhere, changing global state, updating the DOM, sending a message, or logging. Creating and mutating a local temporary variable that nobody outside can observe is not automatically an external side effect.

Side effects aren’t always bad! Sometimes they’re necessary.

Side effects aren’t bad—they are how programs actually accomplish things. A useful pattern is to keep calculation/decision logic pure where practical and put I/O/effects behind clear boundaries, so the effectful parts are easier to identify and test separately.

One sneaky JavaScript caveat: objects are references

A function can look pure while mutating an object passed by the caller:

function addAdmin(user) {
  user.isAdmin = true; // mutates caller-owned state
  return user;
}

A safer pure-style version returns a new value instead:

function addAdmin(user) {
  return { ...user, isAdmin: true };
}

Also, “same input” gets subtle with mutable references. If somebody mutates the object between calls, the reference may be the same while the value is not. Purity is easiest to reason about when inputs are treated as immutable values.

Bonus Tip: Combining Pure Functions

Once you start writing pure functions, you’ll find you can chain them together to do more complex work without losing clarity.

This is where you end up with fun syntax like this.

const double = x => x * 2;
const square = x => x * x;
const increment = x => x + 1;
const halve = x => x / 2;
const negate = x => -x;
const format = x => `Result: ${x}`;

const dramaticChain = [3, 5, 7, 9]
  .map(double)      // [6, 10, 14, 18]
  .map(square)      // [36, 100, 196, 324]
  .map(increment)   // [37, 101, 197, 325]
  .map(halve)       // [18.5, 50.5, 98.5, 162.5]
  .map(negate)      // [-18.5, -50.5, -98.5, -162.5]
  .map(format);     // ["Result: -18.5", ..., etc.]

console.log(dramaticChain);

Pretty fun right?

The chain is intentionally dramatic, but each transformation is small, deterministic, and independently testable. That does not mean chaining six .map() calls is always the clearest or fastest implementation—readability still wins.

Pure functions won’t solve every problem, and forcing every function to be pure can make effect-heavy code awkward. They’re most valuable where deterministic transformations make the code easier to understand, test, cache, or run concurrently.

If a piece of logic can naturally be expressed as explicit inputs → explicit output, purity is a very useful default.

Shared mutable state and hidden effects are common sources of bugs; pure functions reduce those particular failure modes without pretending side effects can disappear from real software.

Anyways, stay pure and keep coding.

If you want to keep learning

  • Race conditions explained — see why reducing shared mutable state can make concurrent code much safer.

  • Test doubles explained — pure functions are easy to test; mocks and stubs help when unavoidable side effects enter the picture.

  • Debugging techniques — predictable functions make bugs easier to isolate when something still goes wrong.

Thanks for the feedback!

OpenAI’s new image gen is available in the API

The OpenAI API lets you generate and edit images from text prompts, using the GPT Image or DALL·E models.

React Labs: View Transitions, Activity, and more – React

React revealed some experimental features that you can try out.

DPRK Hackers Steal $137M from TRON Users in Single-Day Phishing Attack

DPRK hackers stole $137M in 2023 from TRON users via phishing, fueling nuclear programs and cyberattacks.

Better error handling

Bad error handling has cost billions of dollars, crashed planes, killed people, tanked stock markets, wrecked vehicles, and delayed flights.

How I made $64k from deleted files — a bug bounty story

TL;DR — I built an automation that cloned and scanned tens of thousands of public GitHub repos for leaked secrets.

Thanks to everyone who submitted!

bakzkndd, Apoll011, papu163, AlePlaysDev, GabrielDornelas, juulCoding04, ShadowDara, Wakorithegreat, FredericoSRamos, JamesHarryT, numbersanalyst, epicawesomnes, porrrq, ariatheroyal, Heggol, Franspi-lol, RelyingEarth87, sanjayssrini, mmaarrius, and diegoteis1222.

Word Buckets

Write a function that divides a phrase into word buckets, with each bucket containing n or fewer characters. Only include full words inside each bucket.

Examples

split_into_buckets("she sells sea shells by the sea", 10)
output = ["she sells", "sea shells", "by the sea"]

split_into_buckets("the mouse jumped over the cheese", 7)
output = ["the", "mouse", "jumped", "over", "the", "cheese"]

split_into_buckets("fairy dust coated the air", 20)
output = ["fairy dust coated", "the air"]

split_into_buckets("a b c d e", 2)
output = ["a", "b", "c", "d", "e"]

Notes

  • Spaces count as one character.

  • Trim beginning and end spaces for each word bucket (see final example).

  • If buckets are too small to hold a single word, return an empty list: []

  • The final goal isn't to return just the words with a length equal (or lower) to the given n, but to return the entire given phrase bucketized (if possible).

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

  • If you want to be mentioned here, I’d prefer if you sent a GitHub link or Replit!

New Video is out!

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

What'd you think of today's email?

  • 🦥 Amazing! Keep it up
  • 🦥 Good, not great
  • 🦥 It sucked

Login or Subscribe to participate

Want to advertise in Sloth Bytes?

If your company is interested in reaching an audience of developers and programming enthusiasts, you may want to advertise with us here.

Keep Reading

Read all
arrow-right
envelope-simple

Join 50k+ developers and become a better programmer and stay up to date in just 5 minutes.

© 2026 Sloth Bytes.
beehiivPowered by beehiiv