In JavaScript, an object is used to store related data and information in one place.
For example, if you want to store information about a user, you can create an object with properties such as name, age, email, and city.
const user = {
name: "John",
age: 25,
email: "john@example.com",
city: "Jaipur"
};
Here, user is an object.
What Is a JavaScript Object?
A JavaScript object stores data using key-value pairs.
const person = {
name: "John",
age: 25
};
In this example:
nameis a key"John"is its valueageis a key25is its value
An object can contain multiple properties.
How to Create an Object
The easiest way to create an object is by using curly brackets {}.
const car = {
brand: "Toyota",
model: "Camry",
year: 2025
};
The object contains three properties:
brand → Toyota
model → Camry
year → 2025
How to Access Object Properties
There are two common ways to access an object property.
1. Dot Notation
console.log(car.brand);
Output:
Toyota
2. Bracket Notation
console.log(car["model"]);
Output:
Camry
Both methods can be used to access object properties.
How to Change an Object Property
You can easily change the value of an existing property.
car.year = 2026;
console.log(car.year);
Output:
2026
How to Add a New Property
You can also add a new property to an existing object.
car.color = "Black";
console.log(car.color);
Output:
Black
Now the object contains:
const car = {
brand: "Toyota",
model: "Camry",
year: 2026,
color: "Black"
};
How to Delete a Property
Use the delete keyword to remove a property.
delete car.color;
Now the color property has been removed from the object.
Objects Can Contain Functions
An object can also contain functions. A function inside an object is commonly called a method.
const user = {
name: "John",
greet: function() {
console.log("Hello!");
}
};
user.greet();
Output:
Hello!
You can also write the method using modern JavaScript syntax:
const user = {
name: "John",
greet() {
console.log("Hello!");
}
};
user.greet();
Objects Can Contain Different Data Types
JavaScript objects can store different types of values.
const product = {
name: "Laptop",
price: 50000,
available: true,
categories: ["Laptop", "Electronics"]
};
Here we have:
name→ stringprice→ numberavailable→ booleancategories→ array
Objects can even contain another object.
const user = {
name: "John",
address: {
city: "Jaipur",
country: "India"
}
};
You can access the city like this:
console.log(user.address.city);
Output:
Jaipur
JavaScript Objects Example
Here is a simple real-world example:
const student = {
name: "Rahul",
age: 22,
course: "JavaScript",
isActive: true
};
console.log(student.name);
console.log(student.course);
Output:
Rahul
JavaScript
Conclusion
JavaScript objects are an important part of JavaScript. They allow you to group related information using key-value pairs.
You will use objects frequently when working with APIs, JSON, databases, web applications, React, Node.js, and JavaScript projects.