JavaScript Object Creation Using new Object() Method

JavaScript Object Creation Using new Object() Method

In this article, I am going to discuss JavaScript Object Creation Using the new Object() Method with Examples. Please read our previous article where we discussed How to Create JavaScript Object Using Object Literal.

Using new Object() method /By creating instance of Object

Another way for creating an object is that we can declare an object using the object function and instantiate the object by using the “new” keyword. The new Object() method will make a new JavaScript object whose properties can be initialized using dot or bracket notation.

Same as like other JavaScript variables, both the object name (which could be a normal variable) as well as property name/key are case sensitive. We can define a property by assigning it a value. Following is the syntax to create a JavaScript object using the new keyword and object method.

Using new Object() method /By creating instance of Object

Using the new Object() method we can store empty objects by passing undefined and null types. Also, we can store a Boolean object in it by passing a Boolean. What we discussed above is given in the below example.

Example: Objects creation in JavaScript using new Object() method.

The following example shows the JavaScript Objects creation in JavaScript using the new Object() method to store empty objects and Boolean objects in it.

<html>
<head>
    <title>Objects creation in JavaScript Using new Object() method to store empty object and Boolean object in it example</title>
</head>
<body>
    <script>
        //Using new Object() method syntax to store undefined, null and Boolean object
        //Using object storing an empty object in myObj by passing undefined and null types
        let myObj = new Object();
        let myObj1 = new Object(undefined);
        let myObj2 = new Object(null);

        //Using Object to create Boolean object/store Boolean objects in myObj
        let myObj3 = new Object(true); // equivalent to myObj3 = new Boolean(true)
        let myObj4 = new Object(new Boolean()); // equivalent to myObj4 = new Boolean(false)

        console.log("Using new Object() method - object store in myObj: ", myObj);//empty object
        console.log("myObj using new Object() method type? : ", typeof myObj);// object

        console.log("Using new Object() method - object store in myObj1: ", myObj1);//empty object
        console.log("myObj1 using new Object() method type? : ", typeof myObj1);// object

        console.log("Using new Object() method - object store in myObj2: ", myObj2);//empty object
        console.log("myObj2 using new Object() method type? : ", typeof myObj2);// object

        console.log("Using new Object() method - object store in myObj3: ", myObj3);//Boolean object
        console.log("myObj3 using new Object() method type? : ", typeof myObj3);// object

        console.log("Using new Object() method - object store in myObj4: ", myObj4);//Boolean object
        console.log("myObj4 using new Object() method type? : ", typeof myObj4);// object
    </script>
</body>
</html>

Now, run the above code and then open the browser developer tool by pressing the F12 key and have a look at the console tab and you should get the following logs as shown in the below image.

Objects creation in JavaScript using new Object() method

In the above code snippet, by using the new Object() method we are storing an empty object in myObj, myObj1, and myObj2 respectively by passing undefined and null types. Similarly, we are also storing Boolean object in myObj4 and myObj4 by passing true which is equivalent to myObj3 = new Boolean(true), and Boolean() which is equivalent to myObj4 = new Boolean(false). Now, let’s create an object named car and give it properties names/key as make, model, and year as follow:

Example: Object’s creation in JavaScript by using new Object() method

<html>
<head>
    <title>Object’s creation in JavaScript, by Using new Object() method example</title>
</head>
<body>
    <script>
        //new Object() method syntax
        var car = new Object();
        car.make = 'Elon Musk';
        car.model = 'Tesla';
        car.year = 2020;

        console.log("Using new Object() method - car object: ", car)
        console.log("Using new Object() method - car object length: ", Object.getOwnPropertyNames(car).length)
        console.log("car using new Object() method type? : ", typeof car);// object
        console.log("Using new Object() method - with dot notation-->Property make value is: " + car.make);
        console.log("Using new Object() method - with dot notation-->Property model value is: " + car.model);
        console.log("Using new Object() method - with dot notation-->Property year value is: " + car.year);
        console.log("Using new Object() method - with bracket notation-->Property name=make value is: " + car['make']);
        console.log("Using new Object() method - with bracket notation-->Property name=model value is: " + car['model']);
        console.log("Using new Object() method - with bracket notation-->Property name=year value is: " + car['year']);
        console.log("Accessing unassigned properties of Object car : " + car.color);//undefined and not null

    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the console tab and you should get the following logs in the Console tab.

Object’s creation in JavaScript by using new Object() method with Examples

In the above example, we have created an object using the new object() method and it is the same as we created with the object literal. Notice that when we try to access the property of an object which is not defined in an object declaration or when we try to access the unassigned properties of an object i.e.: car.color so it returns undefined and not null.

JavaScript objects Properties can also be accessed or set using a bracket notation [ ]. Objects are sometimes called associative arrays since each property is associated with a string value that can be used to access it. So, for example, we could access the properties of the car object as follows:

car[‘make’]
car[‘model’]
car[‘year’].

We already learned this previous lesson of creating an object using object literal that JavaScript object property name/key can be only a string or symbols, or anything that can be converted to a string, including the empty string. If it’s not a string. It gets cast/converted to a string unless they’re Symbols. This means that even though we can create an object {1: ‘is the real number’}, the key here, 1 gets turned into the string ‘1’. Values can be of any type. Whereas Symbol doesn’t get converted to string it remains as it is (we will be learned about Symbol in Symbol Chapter.

However, any property name that is not a valid JavaScript identifier (for example, a property name/key that contains a space or a hyphen (-), or that starts with a number, if we use a string with a space in it for a property name, we need to use quotes around the name.) and that can only be accessed using the square bracket notation [ ]

We already learned in previous Object creation using object literal that JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names. The square bracket notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime) this is possible by using a variable as an object key and wrapping that key in a square bracket [].

Example:

Objects creation in JavaScript, by Using the new Object() method, wrap the key in square brackets to use a variable as object key called Computed property names example.

<html>
<head>
    <title>Objects creation in JavaScript, by Using new Object() method, wrap the key in square brackets to use a variable as object key called Computed property names example</title>
</head>
<body>
    <script>
        // four variables are created and assigned in a single go, separated by commas
        var myObj = new Object(),
            str = 'This is sample string',
            randNum = Math.random(),
            obj = new Object();

        //In order to use variable as object key, wrap the object key in square brackets also called Computed property name/dynamically determined
        myObj.type = 'Dot notation syntax';
        myObj['date created'] = 'String with space';
        myObj[str] = 'String value';
        myObj[randNum] = 'Random Number';
        myObj[obj] = 'Object';
        myObj[''] = 'An empty string';

        console.log('typeof myObj.type:', typeof myObj.type); //string
        console.log("typeof myObj['date created']:", typeof myObj['date created']); //string
        console.log('typeof myObj[str]:', typeof myObj[str]); //string
        console.log('typeof myObj[randNum]:', typeof myObj[randNum]); //string
        console.log('typeof myObj[obj]:', typeof myObj[obj]); //string
        console.log("typeof myObj['']:", typeof myObj['']); //string
        console.log('The Computed property names/key of myObj object is:\n ', myObj);
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the console tab and you should get the following logs in the Console tab.

Objects creation in JavaScript, by Using new Object() method, wrap the key in square brackets to use a variable as object key called Computed property names example

In the above-given example, we are using a variable as an object key. So, in order to use a variable as an object key, we have to wrap the object key in square brackets [] which is also called Computed property name/dynamically determined.

Note that all the object keys wrapped in the square bracket notation are cast/converted to string unless they are symbols. That we can see in the above sample where typeof every object key wrapped in a square bracket is a string.

Also, above we are using property names/key data created for the myObj object that contains a space i.e.: myObj[‘date created’], we need to use quotes around the property name. That can only be accessed using square bracket notation [].

So far we have seen two ways of creating the object one with the object literal and the second with using the new Object() method, both do exactly the same. So no need to use the new Object(). The most preferred one among both would be the object literal, use this for simplicity, readability, and fast execution.

Difference between `new Object()` and object literal {} notation

1- //new object() method syntax
let myObj = new Object();
/*You should put a semicolon here too.
It’s not required, but it is good practice.*/

// or //
2- //object literal {} syntax
const myObject = { property1: “Hello World” };

They both do the same thing. The first one using a new Object() method syntax, creates an object. The second one using object literal {} syntax, creates an object and adds/assigns a property.

But literal notation takes less space in the program. It’s clearly recognizable as to what is happening, so using new Object(), we are really just typing more doing an unnecessary extra function call.

The second method (using the object literal notation) provides a few advantages.

  1. It is shorter

  2. It provides a shorter syntax for creating/initializing properties from variables (Property Shorthand).

  3. It provides a shorter syntax for defining function methods

  4. It is easier and more structured to create objects on the fly

In the next article, I am going to discuss Object Constructors in JavaScript with Examples. Here, in this article, I try to explain How to Create JavaScript Object Using the new Object() Method with Examples and I hope you enjoy this Creating JavaScript Object Using the new Object() Method article.