Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between new operator and object() constructor in JavaScript?
Both the new operator and Object() constructor are used to create objects in JavaScript, but they serve different purposes and contexts.
The new Operator
The new operator is used to create an instance of an object. It works with constructor functions to instantiate objects and automatically handles the object creation process.
<html>
<body>
<script>
var department = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("December 1, 2017");
document.write("Department: " + typeof department + "<br>");
document.write("Books: " + books + "<br>");
document.write("Date: " + day + "<br>");
</script>
</body>
</html>
Department: object Books: C++,Perl,Java Date: Fri Dec 01 2017 00:00:00 GMT+0000 (UTC)
The Object() Constructor
The Object() constructor is a built-in function that creates and initializes an object. When called with new, it creates an empty object that you can then populate with properties.
<html>
<body>
<script>
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Tutorialspoint";
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Book name is : Perl Book author is : Tutorialspoint
Key Differences
| Aspect | new Operator | Object() Constructor |
|---|---|---|
| Purpose | Creates instances of any constructor | Specifically creates plain objects |
| Usage | Works with built-in and custom constructors | Creates empty objects for property assignment |
| Flexibility | Can create arrays, dates, custom objects | Only creates plain objects |
Modern Alternative
Today, object literal syntax is preferred over new Object() for creating plain objects:
<html>
<body>
<script>
// Modern approach - object literal
var book = {
subject: "Perl",
author: "Tutorialspoint"
};
document.write("Modern syntax - Book: " + book.subject + " by " + book.author);
</script>
</body>
</html>
Modern syntax - Book: Perl by Tutorialspoint
Conclusion
The new operator is a general-purpose tool for creating object instances, while Object() specifically creates plain objects. Modern JavaScript favors object literal syntax over new Object() for better readability and performance.
