What is the difference between new operator and object() constructor in JavaScript?


The new operator

The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.

In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.

var department = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date(“December 1, 2017");

The object() constructor

A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.

Example

Live Demo

<html>
   <head>
      <title>Object Constructor</title>
      <script>
         var book = new Object(); // Create the object
         book.subject = "Perl"; // Assign properties to the object
         book.author = "Tutorialspoint";
      </script>
   </head>
   <body>
      <script type="text/javascript">
         document.write("Book name is : " + book.subject + "<br>");
         document.write("Book author is : " + book.author + "<br>");
      </script>
   </body>
</html>

Output

Book name is : Perl
Book author is : Tutorialspoint

Updated on: 17-Jun-2020

890 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements