OBJECTS

Objects

A JavaScript object is just a collection of properties. A property is a "key: value" pair, where the key is always a string, and value can be any data type, like strings, numbers, Booleans or referrence data type like arrays, functions, and other objects. And properties with their values as functions are called as methods.

An object can be created with curly brackets .

Syntax

objectName = {
key1: value1,
key2: value2
}

Example :

var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
console.log("Hello, My name is peter");
}
};

In above example, the object name is person that has three properties name, age, gender and one method displayName() .

Accessing Object’s Properties

To access the value of a property, we can use the dot (.), or square bracket ([ ]) notation.

Example :

console.log(person.name); // Prints: Peter
console.log(person["gender"]); // Prints: Male

Setting Object’s Properties

We can set the new properties or update the existing one using the dot (.) or bracket ([]) notation.

Example :

var person = {
name: "Peter",
age: 28,
gender: "Male"
};
// Setting a new property
person.country = "India";
console.log(person);
// Updating existing property
person.age = 30;
console.log(person.age); // Prints: 30

Calling Object’s Methods

Example :

var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
console.log("Hello, My name is peter");
}
};
person.displayName(); // Prints: Hello, My name is peter

Finding Object’s length

Example :

var person = {
name: "Peter",
age: 28,
gender: "Male",
country: "India",
displayName: function () {
console.log("Hello, My name is perter");
},
};
// Finding Object's length
console.log(Object.keys(person).length); // Prints: 5