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 }
function addToArray(arr, value) {
arr.push(value);
}
let numbers = [1, 2, 3];
addToArray(numbers, 4);
console.log(numbers); // Output: [1, 2, 3, 4]
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" }
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]
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" }
No comments:
Post a Comment