Suggest an editImprove this articleRefine the answer for “Immutability in functions”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Immutability** is a principle where **data does not change after it is created**. In functions this means they **should not modify their input arguments**, and instead **return new values**, keeping the original data unchanged. **Key point:** immutable functions make code pure and predictable, simplify debugging, and rule out side effects.Shown above the full answer for quick recall.Answer (EN)Image### Detailed explanation Immutability is one of the key principles of **pure and predictable functions**. If a function mutates the data passed to it (an array, an object, etc.), it **affects external state** → it becomes **impure** and **hard to debug**. --- ### Example with mutation (not immutable) ```javascript function addItem(arr, item) { arr.push(item); // mutates the original array return arr; } const numbers = [1, 2, 3]; const result = addItem(numbers, 4); console.log(numbers); // [1, 2, 3, 4] - the original data changed! ``` This is a **mutable** approach - the function *changes* its arguments. --- ### Immutable version ```javascript function addItem(arr, item) { return [...arr, item]; // creates a new array } const numbers = [1, 2, 3]; const result = addItem(numbers, 4); console.log(numbers); // [1, 2, 3] - the original data is preserved console.log(result); // [1, 2, 3, 4] ``` The function **did not change the input data**, it **returned a new copy** - that is **immutability**. --- ### Examples of immutable operations | Data type | Immutable way | |---|---| | Array | `map()`, `filter()`, `concat()`, spread (`[...]`) | | Object | `{ ...obj, key: newValue }` | | String | Always immutable (strings cannot be changed in JS) | --- ### Examples of mutable operations (to avoid in pure functions) | Data type | Operation | |---|---| | Array | `push()`, `pop()`, `splice()`, `sort()`, `reverse()` | | Object | Direct assignment `obj.key = value` | --- ### Why immutability matters Makes functions **pure and predictable** Simplifies **debugging and testing** Rules out **side effects** Allows operations to be **safely parallelized** Makes it easier to **roll back and compare states** (for example, in React, Redux) --- ### SUMMARY | Property | Immutable function | |---|---| | Changes input data | No | | Creates new structures | Yes | | Side effects | None | | Predictability | High | | Examples | `map`, `filter`, `reduce` |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.