Object in JavaScript
Objects in Javascript are name-value pairs and these name-value pairs are called Object Properties.
var person = {
name: "Deepak",
place: "Pune"
};variable person is a JavaScript object which has two properties name and place. The name property has the value "Deepak", and the place property has the value "Pune".
Setting Properties to object
To set the values of the properties into the person object, you can use either dot notation or bracket notation.
person.job = "Front-end Engineer";
person["job"] = "Front-end Engineer";Getting property value from object
To retrieve the values of the properties from the person object, you can use either dot notation or bracket notation.
person.name // will return the value "Deepak"
person.place // will return the value "Pune"
person["name"] // will return the value "Deepak"
person["place"] // will return the value "Pune"Deleting property from object
To remove a property, we can use the delete operator.
delete person.place;Creating Object in JavaScript
There are three way to create object in Javascript
1. Using an object literal — This is the most simple and common way of creating object in JavaScript
var person = {
name: "Deepak",
place: "Pune"
};2. Using new keyword
const person = new Object();
person.name = "Deepak";
person.place = "Pune";3. Inheriting Object.prototype
const person = Object.create(Object.prototype);
person.name = "Deepak";
person.place = "Pune";All three methods mentioned above create the same person object. We will learn more about prototype in upcoming chapters.
Questions
1. What is the value of name key in person object
const person = {
name: 'Deepak',
}
person.name = 'Mayur';
console.log(person.name);Answer — 'Mayur'