The difference is that the first one simply calls Object()
as a function, within the scope of the window
object.
The second one actually instantiates a new object. It's the one you want to use to create an object.
The difference may not be obvious with the Object()
function, but let's say you create your own type, like so:
function User(name) {
this.name = name;
}
var u1 = User("John");
var u2 = new User("Jane");
console.log(u1); // *undefined* because `User()` doesn't return anything.
console.log(this.name); // John
console.log(window.name); // John
console.log(u2.name); // "Jane"
The Object
function itself is a special case--it does create a new Object. But since most functions don't work that way, it's good to get in the habit of using the new
keyword when instantiating things. If you're just creating a plain old Object
, on the other hand, most people prefer the more concise syntax:
var myObj = {};