If the literal notation will work for your situation, then it is more usually compact and is generally preferred over your second method. There are some types of properties that cannot be expressed in the literal notation so they must be set by manually assigning a property as in your second scheme.
For example if you want to refer to some other property on the object, you can't do that in a literal definition so you have to do that with a property assignment on an already constructed object.
var snoopy = {
species: "beagle",
age: 10
};
snoopy.peopleAge = convertDogAgeToPeopleAge(snoopy.age);
What you refer to as the "constructor notation" is not really what most people would say is how you use a constructor to initialize an object. Usually, a constructor is used when you want to be able to make more than one of a given type of object such as:
function Animal(species, age) {
this.species = species;
this.age = age;
}
var buddy = new Animal("golden retriever", 5);
console.log(buddy.species); // "golden retriever"
var snoopy = new Animal("beagle", 10);
console.log(snoopy.species); // "beagle"
What you have called a constructor is just another way to create a new empty object. Both of these do the same thing:
var x = {};
var y = new Object();
Again, the first way is generally preferred because it's more compact and potentially easier for the interpreter to optimize and the Javascript community seems to just have decided that a literal declaration of {}
or []
is preferred unless there is an explicit reason to have to use the new xxxx()
form.