A function is pure if:
Pure: No external dependency, no mutation.
const add = (a: number, b: number) => a + b;
console.log(add(2, 3)); // 5
Impure example (modifies external state):
let total = 0;
const addToTotal = (num: number) => (total += num);
const arr = [1, 2, 3];
const newArr = [...arr, 4]; // [1, 2, 3, 4]
const person = { name: "Alice", age: 25 };
const updatedPerson = { ...person, age: 26 }; // New object, age updated
const toUpper = (str: string) => str.toUpperCase();
const exclaim = (str: string) => str + "!";
const shout = (str: string) => exclaim(toUpper(str));
console.log(shout("hello")); // "HELLO!"
A function that "remembers" variables from its outer scope.
const counter = () => {
let count = 0;
return () => ++count;
};
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2