Saturday, June 29, 2024

JavaScript Mutable functions in JavaScript


In JavaScript, mutable functions are those that can alter the state of objects or variables passed to them. Here are a few examples:
Example 1: Modifying an Object
function updatePerson(person) {
  person.name = "John Doe";
  person.age = 30;
}

let person = { name: "Jane", age: 25 };
updatePerson(person);

console.log(person); // Output: { name: "John Doe", age: 30 }
Example 2: Modifying an Array
function addToArray(arr, value) {
  arr.push(value);
}

let numbers = [1, 2, 3];
addToArray(numbers, 4);

console.log(numbers); // Output: [1, 2, 3, 4]
Example 3: Changing Object Properties
function updateCar(car) {
  car.color = "red";
  car.model = "Sedan";
}

let car = { color: "blue", model: "SUV" };
updateCar(car);
console.log(car); // Output: { color: "red", model: "Sedan" }
Example 4: MutatingElements in an Array
function doubleArrayElements(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i] * 2;
  }
}

let values = [1, 2, 3];
doubleArrayElements(values);
console.log(values); // Output: [2, 4, 6]
Example 5: Adding Properties to an Object
function addProperty(obj, key, value) {
  obj[key] = value;
}

let book = { title: "1984" };
addProperty(book, "author", "George Orwell");

console.log(book); // Output: { title: "1984", author: "George Orwell" }
In these examples, the functions directly modify the state of the objects or arrays passed to them, demonstrating the concept of mutability in JavaScript.

No comments:

Post a Comment

Hot Topics