OK, there are just 2 different ways to do the same thing! One called object literal
and the other one is a function constructor
!
But read on, there are couple of things I'd like to share:
Using {}
makes your code more readable, while creating instances of Object
or other built-in functions not recommended...
Also, Object function gets parameters as it's a function, like Object(params)
... but {}
is pure way to start an object in JavaScript...
Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...
While Object in Javascript can be almost anything, {}
only points to javascript objects, for the test how it works, do below in your javascript code or console:
var n = new Object(1); //Number {[[PrimitiveValue]]: 1}
Surprisingly, it's creating a Number!
var a = new Object([1,2,3]); //[1, 2, 3]
And this is creating a Array!
var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}
and this weird result for String
!
So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {}
is better in my experience!