DEV Community

Carmine Scarpitta
Carmine Scarpitta

Posted on

6 Ways To Create An Object In JavaScript

What is an Object?

Objects are one of JavaScript's data types. An object can be seen as a collection of properties. A property is a name-value pair.

In other words, a JavaScript object is something very similar to a real-life object or entity.

Think a person. A person has different properties like the name or the age. Well... a person can be modeled as a JavaScript object.

There are many ways to create an object in JavaScript.

1. Object() Constructor

  1. Use the Object() constructor to create an empty object.
  2. Set the object's properties.

Example:

// Use the `Object()` constructor to create an empty object
var person = Object();

// Set the object's properties
person.name = "John Doe";
person.age = 42;
Enter fullscreen mode Exit fullscreen mode

2. Create Method

Object.create() can be used to create an object from the prototype of another object.

Example:

var person = Object.create(Person)
Enter fullscreen mode Exit fullscreen mode

3. Object Initializer

  1. Write the curly brackets {}.
  2. Put all properties (name: value pairs) inside the curly brackets.
  3. Add commas to separate name: value pairs.

This is called Object literal (or Object initializer) and can be used to create an object.

Example:

var person = {
    name: "John Doe",
    age: 42
}
Enter fullscreen mode Exit fullscreen mode

4. Constructor Function

  1. Create a Constructor Function.
  2. Use the 'new' keyword to create an object from the constructor function.

Example:

// Create a Constructor Function
function Person() {
    this.name = "John Doe";
    this.age = 42;
}

// Use the 'new' keyword to create an object from the constructor function
var person = new Person();
Enter fullscreen mode Exit fullscreen mode

5. ES6 Class (only for JavaScript ES6)

  1. Create a ES6 class containing a constructor method.
  2. The constructor takes the property values of the object as arguments.

Example:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

var person = Person("John Doe", 42);
Enter fullscreen mode Exit fullscreen mode

6. Singleton Object

A Singleton is an object that can be created only one time. An attempt to create a second object will return a reference to the first object.

Example:

var person = new function(){
    this.name = "John Doe";
    this.age = 42;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this blog post we have shown 6 different ways to create an object in JavaScript. Every developer should be aware of these ways and choose the most appropriate way from time to time.

That's all for this post. If you liked this post, follow me on dev.to and Twitter (@cscarpitta94) to get notified when I publish new posts. 😊

Top comments (0)