Understanding Objects in JavaScript
In JavaScript, objects are one of the most powerful and commonly used data structures. They allow developers to store related data together in a structured way.
What Are Objects and Why Are They Needed?
An object in JavaScript is a collection of key–value pairs used to store related data together.
Think of an object like a real-life entity. For example, a user profile may contain a name, age, and email.
Example:
const user = {
name: "Rahul",
age: 25,
email: "rahul@example.com"
};
Here:
name,age, andemailare keys (properties)"Rahul",25, and"rahul@example.com"are values
Why Are Objects Needed?
Objects help us:
Organize related data
Represent real-world entities
Store multiple values in a single variable
Write cleaner and more structured code
Creating Objects
The most common way to create an object is using curly braces {}.
Example
const person = {
name: "Aman",
age: 22,
city: "Delhi"
};
This object contains three properties: name, age, and city.
Accessing Object Properties
There are two main ways to access object properties.
Dot Notation
Dot notation is the most common way.
console.log(person.name);
console.log(person.age);
Output:
Aman
22
Bracket Notation
Bracket notation uses square brackets [].
console.log(person["city"]);
Bracket notation is useful when the property name is dynamic.
Example:
let key = "name";
console.log(person[key]);
Updating Object Properties
we can update an object property by assigning a new value.
Example:
person.age = 23;
console.log(person.age); // 23
The value of age has now been updated.
Adding New Properties
New properties can be added to an object at any time.
Example:
person.country = "India";
console.log(person);
Now the object includes the country property.
Deleting Properties
we can remove properties from an object using the delete keyword.
Example:
delete person.city;
console.log(person);
The city property is removed from the object.
Looping Through Object Keys
Sometimes we may want to access all properties of an object. One common way to do this is using a for...in loop.
Example:
const student = {
name: "Neha",
age: 20,
grade: "A"
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
Output:
name: Neha
age: 20
grade: A
Here:
keyrepresents each property namestudent[key]gives the value of that property