JavaScript Objects – What is 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.
NOTE – Every key is converted to string except for symbols.
We can also modify objects in the following way:
We can also add a new property to the object foodItem
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,
where this refers to foodItem object.
We can access the object methods by objectName.methodName()