Skip to content

JavaScript mutable object

  • by

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

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:

ActionArray SyntaxObject Syntax
Creatinglet myArray = [];let myObject = {};
Accessing an element/propertymyArray[index]myObject.propertyName
Modifying an element/propertymyArray[index] = valuemyObject.propertyName = value
Adding an element/propertymyArray.push(value)myObject.newProperty = value
Removing an element/propertymyArray.pop()delete myObject.propertyName
Adding elements to the beginningmyArray.unshift(value)
Removing elements from the beginningmyArray.shift()
Modifying multiple elements/propertiesmyArray.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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading