How to Create an Empty Object in JavaScript

Here are two primary ways to create an empty Object in JavaScript.

  1. Using the Object Literal syntax ({ })
  2. Using the Object Constructor (new Object())

Method 1: Using the Object Literal syntax ({ })

The most easy and clean way to create an empty Object in JavaScript is to use the Object literal syntax ({ }). The {} syntax is shorter and neater, allowing you to populate the object inline instantly.

let obj = {};

console.log(obj)

Output

{}

Method 2: Using the Object Constructor

The Object constructor in JavaScript can be used with a parameter, and its behavior varies based on the type of the provided value.

When you use a new Object() with no arguments, it creates an empty object. However, when you pass a value to the Object constructor, it tries to create a wrapper object for that value.

For example:

  1. new Object(123) returns an object wrapping the number 123.
  2. new Object(“hello”) returns an object wrapping the string “hello”.
let new_obj = new Object();

console.log(new_obj);

Output

{}

Both methods will create an empty object, but the object literal syntax ({}) is more concise and is generally preferred.

Difference between Object literal and Object constructor

  1. Clarity and Conciseness:

    • Object Literal: More concise and preferred for creating objects with known properties.
    • Object Constructor: More verbose and less commonly used for simple object creation.
  2. Flexibility:

    • Object Literal: Best suited for creating objects with predefined properties and methods.
    • Object Constructor: The Object constructor can take a parameter. Depending on the type of the provided value, it might create a wrapper object for numbers, strings, or booleans. This behavior can be misleading and is generally not recommended.
  3. Performance:
    • Object Literal: Typically, creating objects using the literal notation is faster because there’s less overhead involved than calling a constructor function.
    • Object Constructor: Slightly slower due to the overhead of invoking a function.
  4. Use Cases:

    • Object Literal: Most common use case, especially when you know the object’s structure in advance.
    • Object Constructor: This can be used when you want to create an object dynamically, but because of its potential pitfalls, it’s often avoided in favor of other methods or patterns.

That’s all!

Related posts

How to Check If an Object is Empty

Display an Object

JavaScript Object Length

Leave a Comment