Skip to content

Create empty object JavaScript | Basics

  • by

You can use object literal or object constructor to create an empty object in JavaScript. There is no benefit to using new Object(); – whereas {}; can make your code more compact, and more readable.

var objectA = {} //This is an object literal // NB: Preferred Way

var objectB = new Object() //This is the object constructor

The only difference is One of them is an object literal, and the other one is a constructor.

Create empty object JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    const obj = {};
    console.log(obj)

    var o = new Object();
    console.log(o)
    
  </script>
</body>
</html>

Output:

Create empty object JavaScript

Create an empty object or object with null values for already known keys

You can do it both ways. I prefer creating the empty object using {} and then adding the needed props but you can make it by defining the props with the initialization of the value: There initialize a property to null.

 var car = {};

or

var car = { 
    color: null,
    seating: null,
    fuelconsumption: null
};

Just like you did. I don’t think there is a best practice for doing this. But maybe the values should point to the needed type of data saved in this property.

Example:

var car = { 
    color:"",
    seating: "",
    fuelconsumption: ""
};

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *