Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object initialization, which is the best way to do it?

Object initialization:

var myObject = {};

and

var myObject = new Object();

why the last one is considered an antipattern?

thanks

like image 711
cirpo Avatar asked Dec 16 '22 18:12

cirpo


2 Answers

I'm not sure new Object() really falls under "anti-pattern", but {} is usually preferred, it's terse and more flexible at the same time.

When you're writing JavaScript you want it to end up short...if it can be terse and understandable when writing it as well, as this is:

var myObject = { key: "value" };

...then you get the best of both worlds. Also when you're creating objects within objects, for example:

var myObject = { subObj: { key: "value" } };

...then you can see it's much more readable than the alternative new Object() syntax.

like image 109
Nick Craver Avatar answered Mar 02 '23 00:03

Nick Craver


You always should prefer literals over constructors.

This is not really related to your question but here is an example with arrays. new Array() can be confusing at the first glance if you don't know how it works:

var a = [5,6];
var b = [5];

both create arrays with length 2 and 1 resp. But consider

var a = new Array(5,6);
var b = new Array(5);

The first one creates an array of length 2 ,containing the elements 5 and 6, the last one creates an empty array of length 5.

So you see, using literal notation avoids this pitfall.

Besides that, always using literal notation is consistent. When you create a string you also write var t = "Hello world" and not var t = new String("Hello world").

like image 43
Felix Kling Avatar answered Mar 01 '23 22:03

Felix Kling