In JavaScript, objects are collections of properties, where each property has a key (also known as a "name") and a value. Objects allow you to store related data and functionality together in a structured way, making them one of the most important and flexible types in JavaScript.
You can create an object using curly braces {}
and define key-value pairs within.
let person = {
name: "Ravi",
age: 30,
isStudent: false
};
In this example, person
is an object with three properties: name
, age
, and isStudent
.
You can access properties in two ways:
objectName.property
objectName["property"]
console.log(person.name); // Output: Ravi
console.log(person["age"]); // Output: 30
You can add or update properties using dot notation or bracket notation.
person.city = "Delhi"; // Adds new property 'city'
person.age = 31; // Updates 'age' property
console.log(person.city); // Output: Delhi
console.log(person.age); // Output: 31
You can remove a property using the delete
keyword.
delete person.isStudent;
console.log(person.isStudent); // Output: undefined
Objects can have methods, which are functions that belong to an object. Define a method using a function inside the object.
let car = {
brand: "Toyota",
model: "Camry",
start: function() {
console.log("The car has started.");
}
};
car.start(); // Output: The car has started.
this
Keyword