JS Coding Questions Logo
JS Coding Questions
#1💼 Interview💻 Code

What are the possible ways to create objects in JavaScript

Advertisement

728x90

There are many ways to create objects in javascript as mentioned below:

1. Object literal syntax:

The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.

javascript
1var object = {
2  name: "Sudheer",
3  age: 34,
4  };

Object literal property values can be of any data type, including array, function, and nested object.

Note: This is one of the easiest ways to create an object and it's most commonly used for creating simple, ad-hoc objects.

2. Object constructor:

The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.

javascript
1var object = new Object();

The Object() is a built-in constructor function so "new" keyword is not required for creating plain objects. The above code snippet can be re-written as:

javascript
1var object = Object();

However, Object() can be used to either create a plain object or convert a given value into its corresponding object wrapper, whereas new Object() is specifically used to explicitly create a new object instance.

3. Object's create method:

The create method of Object is used to create a new object by passing the specified prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects. In other words, this is useful for setting up prototypal inheritance. The second argument is optional and it is used to create properties on a newly created object.

The following code creates a new empty object whose prototype is null.

javascript
1var object = Object.create(null);

The following example creates an object along with additional new properties.

javascript
1let vehicle = {
2  wheels: "4",
3  fuelType: "Gasoline",
4  color: "Green",
5  };
6
7let carProps = {
8  type: {
9  value: "Volkswagen",
10  },
11  model: {
12  value: "Golf",
13  },
14};
15
16var car = Object.create(vehicle, carProps);
17
18console.log(car);

4. Function constructor:

In this approach, create any function and apply the new operator to create object instances. This was the main way to do constructor-based OOP before ES6 classes.

javascript
1function Person(name) {
2  this.name = name;
3  this.age = 21;
4  }
5
6var object = new Person("Sudheer");

5. Function constructor with prototype:

This is similar to function constructor but it uses prototype for their properties and methods. Using prototype means you're sharing methods/properties across instances, which saves memory and improve performance.

javascript
1function Person() {}
2
3Person.prototype.name = "Sudheer";
4
5var object = new Person();

This is equivalent to creating an instance with Object.create method with a function prototype and then calling that function with an instance and parameters as arguments.

javascript
1function func(x, y, z) {
2  this.x = x;
3  this.y = y;
4  this.z = z;
5  }
6
7var instance = new func(1, 2, 3);

(OR)

javascript
1function func(x, y, z) {
2  this.x = x;
3  this.y = y;
4  this.z = z;
5  }
6  // Create a new instance using function prototype.
7
8var newInstance = Object.create(func.prototype)
9
10// Call the function
11
12var result = func.call(newInstance, 1, 2, 3),
13
14// If the result is a non-null object then use it otherwise just use the new instance.
15
16console.log(result && typeof result === 'object' ? result : newInstance);

6. Object's assign method:

The Object.assign method is used to copy all the properties from one or more source objects and stores them into a target object. This is mainly used for cloning and merging

The following code creates a new staff object by copying properties of his working company and the car he owns.

javascript
1const orgObject = { company: "XYZ Corp" };
2
3const carObject = { name: "Toyota" };
4
5const staff = Object.assign({}, orgObject, carObject);

7. ES6 Class syntax:

ES6 introduces class feature to create objects. This is syntactic sugar over the prototype-based system.

javascript
1class Person {
2  constructor(name) {
3  this.name = name;
4  }
5  }
6
7var object = new Person("Sudheer");

8. Singleton pattern:

A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't accidentally create multiple instances.

##### Singleton with Closure (Classic JS Pattern)

javascript
1const Singleton = (function () {
2  let instance;
3
4  function createInstance() {
5  return { name: "Sudheer" };
6  }
7
8  return {
9  getInstance: function () {
10  if (!instance) {
11  instance = createInstance();
12  }
13  return instance;
14  }
15  };
16  })();
17
18  // Usage
19  const obj1 = Singleton.getInstance();
20  const obj2 = Singleton.getInstance();
21
22  console.log(obj1 === obj2); // true

In modern JavaScript applications, singletons are commonly implemented using ES6 modules for their built-in caching behavior, or closures for encapsulated state management.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 2

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
1of476
What are the possible ways to create objects in JavaScript | JSCodingQuestions.com