---
title: "How to create an object in JavaScript?"  
description: "How to create an object in JavaScript?"  
author: "ICSM Computer"  
published: 2024-10-17  
updated: 2024-12-26  
canonical: https://www.mindstick.com/forum/161010/how-to-create-an-object-in-javascript  
category: "javascript"  
tags: ["javascript"]  
reading_time: 6 minutes  

---

# How to create an object in JavaScript?

How to create an object in JavaScript? so that no [anyone](https://www.mindstick.com/articles/23207/how-to-find-the-best-fit-job-for-anyone) can change it.

## Replies

### Reply by Khushi Singh

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:

```javascript
// 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:\

```javascript
// 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\

```plaintext
// 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](https://www.mindstick.com/articles/1047/java-script-objects).\
\
\
\
\
\

### Reply by Anubhav Sharma

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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.


---

Original Source: https://www.mindstick.com/forum/161010/how-to-create-an-object-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
