Javascript Objects – How to Create an Object in Javascript?

JavaScript Objects are basically a collection of properties. Each property is a key-value pair. For example- FirstName is a key and Sita is a value.

SYNTAX -  const objectName{

                            Key: value;

                          }

Example- The following example creates a new object named foodItem with one property called breadPrice

const foodItem{
breadPrice: 100;

}

 We can access each property of the object by two different ways.

objectName.propertyName

eg – foodItem.breadPrice

objectName["propertyName"]

eg – foodItem[“breadPrice]

NOTE – Every key is converted to string except for symbols.

We can also modify objects in the following way:

foodItem.breadPrice = 98;

We can also add a new property to the object foodItem

foodItem.CarrotPrice=102;

METHODS IN OBJECTS

Methods are actions that are to be performed on an object. They are stored in properties as function definitions. 

For example – in object foodItem adding a method called totPrice to calculate the total price of the food items as,

totPrice: function(){ 

this.breadPrice+this.CarrotPrice

}

where this refers to foodItem object.

We can access the object methods by objectName.methodName()

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *