Saturday, June 29, 2024

Immutable Functions in JavaScript

An immutable function in JavaScript is a function that does not modify the data passed to it as arguments. Instead, it returns a new data structure with the changes applied, leaving the original data unchanged. This concept is crucial in functional programming and helps avoid side effects, making the code more predictable and easier to debug.

Examples of Immutable Functions
Example 1: Immutable Update to an Object
const person = {
  name: "Alice",
  age: 30
};

const updateAge = (obj, newAge) => {
  return {
    ...obj,
    age: newAge
  };
};

const updatedPerson = updateAge(person, 31);

console.log(person); // { name: "Alice", age: 30 }
console.log(updatedPerson); // { name: "Alice", age: 31 }
In this example, the updateAge function does not modify the original person object. Instead, it creates a new object with the updated age.
Example 2: Immutable Update to an Array

const numbers = [1, 2, 3];
const addNumber = (arr, num) => {
  return [...arr, num];
};

const newNumbers = addNumber(numbers, 4);

console.log(numbers); // [1, 2, 3]
console.log(newNumbers); // [1, 2, 3, 4]
Here, the addNumber function returns a new array with the new number added, leaving the original numbers array unchanged.

Benefits of Immutable Functions
  1. Predictability: Since immutable functions do not modify the original data, the same input will always produce the same output, making the code easier to understand and predict.
  2. Debugging: Easier to trace the flow of data and identify where things might have gone wrong since the original data remains unchanged.
  3. Concurrency: Immutable data structures are inherently thread-safe, making it easier to work with concurrency and parallelism.
  4. Undo/Redo: Immutable updates make it easier to implement features like undo and redo, as each change creates a new state rather than modifying the current state.
Using immutability in JavaScript often involves the use of methods that return new objects or arrays rather than modifying the originals. Some commonly used immutable methods include map, filter, reduce, and the spread operator (...).
Look at mutable functions in JavaScript click here.

No comments:

Post a Comment

Hot Topics