In JavaScript, the term “mutable” refers to an object or variable that can be changed or modified after it has been created. In other words, you can alter the state or value of a mutable object.
JavaScript has several types of mutable objects, such as arrays and objects (also known as key-value pairs or dictionaries). You can add, remove, or modify elements or properties within these objects.
JavaScript mutable object example
Simple example code.
// Mutable array
let myArray = [1, 2, 3];
console.log(myArray); // Output: [1, 2, 3]
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
myArray[1] = 5;
console.log(myArray); // Output: [1, 5, 3, 4]
// Mutable object
let myObject = { name: "John", age: 25 };
console.log(myObject); // Output: { name: "John", age: 25 }
myObject.name = "Jane";
console.log(myObject); // Output: { name: "Jane", age: 25 }
myObject.city = "New York";
console.log(myObject); // Output: { name: "Jane", age: 25, city: "New York" }
Output:
![JavaScript mutable object](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/05/JavaScript-mutable-object.jpg?resize=472%2C246&ssl=1)
As you can see, in both cases, the initial values of the mutable array and object can be modified or extended. This is because arrays and objects are mutable data types in JavaScript.
Another example
// Mutable object example
let person = {
name: "John",
age: 30,
city: "New York"
};
console.log(person); // Output: { name: "John", age: 30, city: "New York" }
// Modifying properties
person.age = 35;
person.city = "San Francisco";
console.log(person); // Output: { name: "John", age: 35, city: "San Francisco" }
// Adding new properties
person.job = "Engineer";
console.log(person); // Output: { name: "John", age: 35, city: "San Francisco", job: "Engineer" }
// Removing a property
delete person.city;
console.log(person); // Output: { name: "John", age: 35, job: "Engineer" }
Here’s a tabular format illustrating the syntax for working with mutable objects in JavaScript:
Action | Array Syntax | Object Syntax |
---|---|---|
Creating | let myArray = []; | let myObject = {}; |
Accessing an element/property | myArray[index] | myObject.propertyName |
Modifying an element/property | myArray[index] = value | myObject.propertyName = value |
Adding an element/property | myArray.push(value) | myObject.newProperty = value |
Removing an element/property | myArray.pop() | delete myObject.propertyName |
Adding elements to the beginning | myArray.unshift(value) | – |
Removing elements from the beginning | myArray.shift() | – |
Modifying multiple elements/properties | myArray.splice(startIndex, numToDelete, ...itemsToAdd) | – |
Note: The “Object Syntax” column shows examples specific to objects, while the “Array Syntax” column shows examples specific to arrays.
Comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version