Creating JavaScript Objects with an object initializer

An object initializer is a little shorter than a constructor function. The following is the syntax of an object initializer.


MyMotorbike = {engine:125cc}

Pretty simple! MyMotorbike is the object name, engine is the property,
and 125cc is the value of the property.

One important thing to be remembered is that an object created with the initializer function is already an instance of the object so the properties can be used without creating a new instance of the object.

Next, we are going to create an object called MyComputer using the initializer method. It’s going to have three sets of properties and values.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}

Since there is no need to create an instance of the object we can use its properties to assign them to variables or write them to the page. We can even create more objects.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}
MyNextComputer = {CPU:"i7" , RAM:"16GB" , SSD:"512GB"}

Next I can write what I want my next computer to be using these properties.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}
MyNextComputer = {CPU:"i7" , RAM:"16GB" , SSD:"512GB"}
document.write("Right now my computer has an " + MyComputer.CPU + " processor, " + MyComputer.RAM + " of RAM memory, and a " + MyComputer.SSD + " Solid State Drive.");
document.write("But, my next computer is going to have an " + MyNextComputer.CPU + " processor, " + MyNextComputer.RAM + " of RAM memory, and a " + MyNextComputer.SSD + " Solid State Drive.");

Leave a Reply