I’m trying to understand the distinctions between Object() and new Object() in ES6. What happens when we call the Object constructor with and without the new keyword?
I know there are discussions about new Object vs new Object() and new Object() vs {}, but I’m specifically curious about Object() compared to new Object().
The MDN docs mention that Object() can be used with or without new, sometimes leading to different outcomes. However, I can’t figure out what these differences might be.
// What's the difference between these?
let obj1 = Object();
let obj2 = new Object();
// Are there any scenarios where they behave differently?
console.log(obj1 === obj2); // true or false?
Can someone explain the nuances between these two approaches in ES6? Are there any specific use cases where one is preferred over the other?
I’ve spent a fair bit of time working with both forms and can confirm that in modern JavaScript they mostly yield the same result. Essentially, when you call Object() without new, it’s performing a type conversion if you pass a primitive; for instance, Object(42) wraps 42 in a Number object. In contrast, new Object() always creates a new object. Hence, in your example, obj1 and obj2 are distinct instances, so obj1 === obj2 evaluates to false. I’ve found that using object literals (i.e., {}) is usually the clearer approach when creating objects.
hey tom, i’ve played around with this too. tbh, Object() and new Object() are pretty much the same in es6. they both make empty objects. the main diff is how they handle args - Object() tries to convert stuff, new Object() always makes a fresh object. but honestly, most devs just use {} these days. it’s cleaner and does the job. don’t sweat it too much!
In my experience, the difference between Object() and new Object() is quite subtle in ES6. Both essentially create empty objects, but there’s a nuance in how they handle arguments. Object() will attempt to convert its argument to an object if one is provided, while new Object() always creates a fresh object instance. For most practical purposes, they behave identically when called without arguments.
However, it’s worth noting that using either form is generally considered less idiomatic in modern JavaScript. Object literals ({}) are typically preferred for creating new objects, as they’re more concise and clearly express intent. Unless you have a specific reason to use the constructor syntax, I’d recommend sticking with object literals in your code.