JavaScript Objects: Storing Related Data Together

So far in this series we have stored individual values in variables and lists of similar values in arrays. But what happens when you need to store several different pieces of information that all belong to the same thing?
Say you want to represent a person. A person has a name, an age, a city, and maybe an email. You could store each piece separately:
let name = "Arjun";
let age = 21;
let city = "Mumbai";
let email = "[email protected]";
This works until you need to represent five people. Now you have twenty variables with no clear connection between them. There is no way to know that name, age, city, and email all belong to the same person.
Objects solve this. An object groups all the related data under one variable, with named labels for each piece.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
email: "[email protected]",
};
One variable. Four labeled pieces of data. All clearly related.
What is an Object?
An object is a collection of key-value pairs. Each piece of data has a key (a label, always a string) and a value (whatever you want to store there).
Object: person
┌─────────────────────────────────────────────────┐
│ Key │ Value │
├────────────────┼────────────────────────────────┤
│ "name" │ "Arjun" │
│ "age" │ 21 │
│ "city" │ "Mumbai" │
│ "email" │ "[email protected]" │
└────────────────┴────────────────────────────────┘
Access with: person.name → "Arjun"
person.age → 21
The keys are sometimes called properties. The phrase "an object's property" just means one of its key-value pairs.
Arrays vs Objects
Before going further, it helps to see exactly when to use each:
ARRAY OBJECT
──────────────────────────────── ──────────────────────────────────────
let fruits = [ let person = {
"apple", name: "Arjun",
"banana", age: 21,
"mango" city: "Mumbai"
]; };
Ordered list of similar items Named properties on one thing
Access by index: fruits[0] Access by key: person.name
Best for: collections Best for: describing one entity
Use an array when you have a list of similar things (fruits, scores, names). Use an object when you are describing one thing with multiple different attributes (a person, a product, a user profile).
Creating an Object
Objects are created using curly braces {}. Each key-value pair is separated by a comma, and the key and value are separated by a colon.
// Basic syntax
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
// Object with mixed value types
let product = {
title: "Mechanical Keyboard",
price: 3499,
inStock: true,
rating: 4.5,
};
// Object with an array as a value
let student = {
name: "Priya",
marks: [88, 92, 75, 96],
passed: true,
};
// An empty object — you can add properties later
let config = {};
The keys do not need quotes when they are simple words. If a key contains spaces or special characters, you must wrap it in quotes:
let profile = {
firstName: "Arjun", // no quotes needed
"last name": "Sharma", // quotes required — has a space
"fav-color": "blue", // quotes required — has a hyphen
};
Accessing Properties
There are two ways to read a value from an object.
Dot notation
The most common way. Write the object name, a dot, then the key name.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
console.log(person.name); // "Arjun"
console.log(person.age); // 21
console.log(person.city); // "Mumbai"
// Accessing a key that does not exist returns undefined
console.log(person.email); // undefined
Bracket notation
Write the object name, then the key as a string inside square brackets. This is the same idea as accessing an array by index, except you use a string key instead of a number.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
console.log(person["name"]); // "Arjun"
console.log(person["age"]); // 21
console.log(person["city"]); // "Mumbai"
Bracket notation becomes necessary in two situations. First, when the key contains special characters:
let profile = {
"last name": "Sharma",
"fav-color": "blue",
};
// This would fail:
// console.log(profile.last name); — syntax error
// This works:
console.log(profile["last name"]); // "Sharma"
console.log(profile["fav-color"]); // "blue"
Second, when the key is stored in a variable:
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
let key = "age";
console.log(person[key]); // 21 — uses the value of the variable as the key
key = "city";
console.log(person[key]); // "Mumbai"
This is something dot notation simply cannot do. If you write person.key, JavaScript looks for a property literally named "key", not the value of the variable key.
Updating Properties
Updating an existing property uses the same syntax as creating one — assign a new value to the key.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
console.log(person.age); // 21
// Update the age
person.age = 22;
console.log(person.age); // 22
// Update using bracket notation
person["city"] = "Pune";
console.log(person.city); // "Pune"
console.log(person);
// { name: "Arjun", age: 22, city: "Pune" }
Adding New Properties
You can add a property to an object at any time after it was created — just assign to a key that does not yet exist.
let person = {
name: "Arjun",
age: 21,
};
// Adding new properties after creation
person.city = "Mumbai";
person.email = "[email protected]";
person["phone"] = "9876543210";
console.log(person);
// {
// name: "Arjun",
// age: 21,
// city: "Mumbai",
// email: "[email protected]",
// phone: "9876543210"
// }
Deleting Properties
Use the delete operator to remove a property from an object entirely.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
email: "[email protected]",
};
console.log(person.email); // "[email protected]"
delete person.email;
console.log(person.email); // undefined — property no longer exists
console.log(person);
// { name: "Arjun", age: 21, city: "Mumbai" }
After deletion, accessing the removed key returns undefined, just like accessing any key that was never there.
Looping Through an Object
Unlike arrays, objects do not have numbered indices — they have named keys. To iterate over all key-value pairs, use a for...in loop.
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
email: "[email protected]",
};
// for...in gives you each key one at a time
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: Arjun
// age: 21
// city: Mumbai
// email: [email protected]
Notice that inside the loop, person[key] uses bracket notation with a variable — this is exactly the situation where dot notation would not work.
You can also use Object.keys() to get all the keys as an array, then loop over that:
let person = {
name: "Arjun",
age: 21,
city: "Mumbai",
};
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
console.log(key + " → " + person[key]);
}
// Output:
// name → Arjun
// age → 21
// city → Mumbai
And Object.values() if you only need the values:
let person = { name: "Arjun", age: 21, city: "Mumbai" };
let values = Object.values(person);
console.log(values); // ["Arjun", 21, "Mumbai"]
Object Key-Value Structure Diagram
Variable Object in memory
──────── ──────────────────────────────────────────
┌─────────────────────────────────────────┐
│ person │
person ──────► ├───────────────┬─────────────────────────┤
│ KEY │ VALUE │
├───────────────┼─────────────────────────┤
│ "name" │ "Arjun" │
├───────────────┼─────────────────────────┤
│ "age" │ 21 │
├───────────────┼─────────────────────────┤
│ "city" │ "Mumbai" │
├───────────────┼─────────────────────────┤
│ "email" │ "[email protected]" │
└───────────────┴─────────────────────────┘
person.name ─────────────────────────────► "Arjun"
person["age"] ─────────────────────────────► 21
person.city ─────────────────────────────► "Mumbai"
Assignment: Try It Yourself
Open your browser console or playcode.io and work through these steps.
Step 1: Create a student object
let student = {
name: "Priya",
age: 20,
course: "Computer Science",
};
Step 2: Add a new property
student.college = "MIT Pune";
console.log(student);
// { name: "Priya", age: 20, course: "Computer Science", college: "MIT Pune" }
Step 3: Update one property
student.age = 21;
console.log("Updated age:", student.age); // 21
Step 4: Print all keys and values using a loop
console.log("Student details:");
for (let key in student) {
console.log(key + ": " + student[key]);
}
// Output:
// Student details:
// name: Priya
// age: 21
// course: Computer Science
// college: MIT Pune
Bonus: Delete a property and verify it is gone
delete student.college;
console.log(student.college); // undefined
console.log(student);
// { name: "Priya", age: 21, course: "Computer Science" }
Quick Recap
An object is a collection of key-value pairs used to describe a single entity
Created with curly braces:
let obj = { key: value }Access properties with dot notation (
obj.key) or bracket notation (obj["key"])Use bracket notation when the key has special characters or is stored in a variable
Update a property by assigning a new value:
obj.key = newValueAdd a property by assigning to a new key:
obj.newKey = valueDelete a property with the
deleteoperator:delete obj.keyLoop through keys with
for...inorObject.keys()
Comments
Join the discussionNo comments yet. Be the first to comment.
