You can create an object in JavaScript that cannot be modified using the Object.freeze() method. The Object.freeze() method "freezes" an object, which means its properties cannot be changed, nor can you add new properties. Let's break it down: Example:
// Create an object to hold a person's information
const person = {
name: 'Alice',
age: 25
};
// Use Object.freeze so that the object cannot be changed
Object.freeze(person);
// Now, let's try to change the properties of the object
person.name = 'Bob'; // This won't work because the object is frozen
person.city = 'New York'; // Adding a new property also won't work
// Check the object to see if any changes were applied
console.log(person);
// Output will still be: { name: 'Alice', age: 25 }
In this example, by calling Object.freeze(person), then any attempts to change a name or add a new city will do nothing. The object remains exactly as it is when frozen – no more changes allowed! But Wait—What if My Object Has Other Objects Inside It? By default, Object.freeze() only prevents modification of the outer properties of the object. Therefore, if it contains other objects inside, they can still be changed unless you freeze those too.
Example:
// Create an object for the user with nested details
const user = {
name: 'John',
details: {
age: 30
}
};
// Freeze the main object to prevent changes to its top-level properties
Object.freeze(user);
// Try changing a property inside the nested object
user.details.age = 35; // This works because Object.freeze() only applies to the top level
// Check the updated value of the nested property
console.log(user.details.age); // Output: 35
How to Make the Object Fully Immutable (Deep Freeze): If you want to ensure that every property of the object, including those that might be nested inside other objects, are immutable, then you have to perform a "deep freeze." Here's how
// Function to deeply freeze an object (including nested objects)
function deepFreeze(obj) {
// Freeze the current object
Object.freeze(obj);
// Loop through each property of the object
Object.keys(obj).forEach(key => {
// If the property is an object and not null, recursively freeze it
if (typeof obj[key] === 'object' && obj[key] !== null) {
deepFreeze(obj[key]);
}
});
}
// Create an object with nested properties
const deepUser = {
name: 'John',
details: {
age: 30,
address: {
city: 'New York'
}
}
};
// Deep freeze the object to make everything, including nested properties, immutable
deepFreeze(deepUser);
// Attempt to modify properties
deepUser.details.age = 35; // This won't work; the age remains 30
deepUser.details.address.city = 'Los Angeles'; // This won't work; the city stays 'New York'
// Print the object to verify that no changes were made
console.log(deepUser);
// Output: { name: 'John', details: { age: 30, address: { city: 'New York' } } }
Now, deepUser is an object that is and everything inside it immutable, i.e., at any point no changes are allowed inside. If you’re interested in learning more about JavaScript objects, check out this
detailed article on JavaScript Objects.
In JavaScript, there are multiple ways to create an object. Here are the most common methods:
1. Using Object Literal
This is the simplest and most common way to create an object.
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function () {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
}
};
// Access properties
console.log(person.firstName); // Output: John
person.greet(); // Output: Hello, my name is John Doe.
2. Using the Object Constructor
You can create an object using the Object constructor.
const person = new Object();
person.firstName = "Jane";
person.lastName = "Doe";
person.age = 25;
person.greet = function () {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
};
// Access properties
console.log(person.lastName); // Output: Doe
person.greet(); // Output: Hello, my name is Jane Doe.
3. Using a Constructor Function
A constructor function is a reusable template for creating objects.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.greet = function () {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
};
}
const person1 = new Person("Alice", "Smith", 28);
const person2 = new Person("Bob", "Johnson", 35);
console.log(person1.firstName); // Output: Alice
person2.greet(); // Output: Hello, my name is Bob Johnson.
4. Using ES6 Classes
The class syntax is a more modern and readable way to define reusable object templates.
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
}
}
const person1 = new Person("Emily", "Davis", 40);
const person2 = new Person("Chris", "Brown", 50);
console.log(person1.age); // Output: 40
person2.greet(); // Output: Hello, my name is Chris Brown.
5. Using Object.create
This creates a new object with the specified prototype object.
const prototypeObject = {
greet() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
}
};
const person = Object.create(prototypeObject);
person.firstName = "Sophia";
person.lastName = "Williams";
person.age = 22;
person.greet(); // Output: Hello, my name is Sophia Williams.
6. Using Factory Functions
A factory function is a function that returns a new object.
function createPerson(firstName, lastName, age) {
return {
firstName,
lastName,
age,
greet() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
}
};
}
const person = createPerson("Liam", "Jones", 27);
console.log(person.age); // Output: 27
person.greet(); // Output: Hello, my name is Liam Jones.
Summary Table
Method
Suitable for
Object Literal
Simple, static objects
Object Constructor
Basic object creation
Constructor Function
Reusable templates (ES5)
ES6 Classes
Modern, reusable templates
Object.create
Prototype-based inheritance
Factory Function
Functional, flexible design
Each method has its use case, depending on the complexity and reusability of the objects you're working with.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can create an object in JavaScript that cannot be modified using the Object.freeze() method. The Object.freeze() method "freezes" an object, which means its properties cannot be changed, nor can you add new properties. Let's break it down:
Example:
In this example, by calling Object.freeze(person), then any attempts to change a name or add a new city will do nothing. The object remains exactly as it is when frozen – no more changes allowed!
But Wait—What if My Object Has Other Objects Inside It?
By default, Object.freeze() only prevents modification of the outer properties of the object. Therefore, if it contains other objects inside, they can still be changed unless you freeze those too.
Example:
How to Make the Object Fully Immutable (Deep Freeze):
If you want to ensure that every property of the object, including those that might be nested inside other objects, are immutable, then you have to perform a "deep freeze." Here's how
Now, deepUser is an object that is and everything inside it immutable, i.e., at any point no changes are allowed inside.
If you’re interested in learning more about JavaScript objects, check out this detailed article on JavaScript Objects.
In JavaScript, there are multiple ways to create an object. Here are the most common methods:
1. Using Object Literal
This is the simplest and most common way to create an object.
2. Using the
ObjectConstructorYou can create an object using the
Objectconstructor.3. Using a Constructor Function
A constructor function is a reusable template for creating objects.
4. Using ES6 Classes
The
classsyntax is a more modern and readable way to define reusable object templates.5. Using
Object.createThis creates a new object with the specified prototype object.
6. Using Factory Functions
A factory function is a function that returns a new object.
Summary Table
Object.createEach method has its use case, depending on the complexity and reusability of the objects you're working with.