Learn how to group related data and behaviour into a single structure using key-value pairs — the most versatile and widely used data type in JavaScript.
An object in JavaScript is a collection of key-value pairs, where each key (also called a property) is associated with a value. Objects are used to represent real-world entities and can also contain functions — known as methods — that describe the behaviour of that entity.
Objects are the foundation of JavaScript: arrays, dates, functions, and almost everything else you interact with is an object under the hood. Mastering objects means mastering the language itself.
An object is like a profile card — instead of separate variables for each detail, everything about one entity lives together:
{ name: "Aman", age: 22 }
name, age, city
let person = {
name: "Aman",
age: 22,
city: "Vadodara"
};
// Dot notation — most common
console.log(person.name);
// Bracket notation — useful for dynamic keys
console.log(person["age"]);
// Access a key that doesn't exist → undefined (no error)
console.log(person.country);
person.name) — clean and most commonly usedperson["age"]) — required when the key is a variable or contains special charactersundefined — not an errorlet user = {
name: "Aman"
};
user.age = 22; // add a new property
user.name = "Raj"; // update an existing property
console.log(user.name);
console.log(user.age);
console.log(user);
const objects allow property changes — only re-assigning the whole object is forbiddenlet calculator = {
add: function(a, b) {
return a + b;
},
// Shorthand method syntax (modern)
multiply(a, b) {
return a * b;
}
};
console.log(calculator.add(5, 3));
console.log(calculator.multiply(4, 6));
calculator.add(5, 3)multiply(a, b) {}) drops the function keywordlet student = {
name: "Priya",
marks: {
maths: 95,
science: 88,
english: 91
}
};
// Access nested property
console.log(student.marks.maths);
// Loop through all keys
for (let key in student.marks) {
console.log(key + ": " + student.marks[key]);
}
student.marks.mathsfor...in loops over every key in an object — ideal for dynamic key accesslet now = new Date();
console.log(now.getFullYear()); // current year
console.log(now.getMonth() + 1); // month (0-based, so +1)
console.log(now.getDate()); // day of the month
new Date() creates a built-in Date object with the current timestampgetFullYear(), getMonth(), and getDate() extract parts of the dategetMonth() is zero-based — January is 0, so always add 1 for displayThink of a student ID card — all related details grouped in one place:
Click ▶ Preview, then press the button to render a student object as a formatted profile card on the page — looping through its properties dynamically.
<!DOCTYPE html>
<html>
<head><title>Objects Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">
<h2>Student Info</h2>
<button onclick="showInfo()"
style="padding:8px 18px;background:#f7df1e;border:none;
border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
Show
</button>
<div id="output" style="margin-top:16px;font-size:0.95rem"></div>
<script>
function showInfo() {
const student = {
name: "Priya Sharma",
age: 20,
course: "Computer Science",
city: "Vadodara",
grade: "A+"
};
let html =
"<div style='background:#fff;border:1px solid #ddd;border-radius:10px;" +
"padding:18px 22px;max-width:340px;line-height:2.2'>";
for (let key in student) {
html += `<b style="text-transform:capitalize">${key}:</b> ${student[key]}<br>`;
}
html += "</div>";
document.getElementById("output").innerHTML = html;
}
</script>
</body>
</html>
let profile = {
name: "Your Name",
age: 0
};
profile.name using dot notationprofile["age"] using bracket notationconst product = {
name: "Laptop",
price: 45000
};
quantity with value 3price to 42000let obj = { name: "Aman", age: 22 };
console.log(obj.name);
console.log(obj["age"]);
obj.name is the standard way. Bracket notation obj["name"] also works — note the key must be a string inside quotes when used directly.
let obj = { a: 10 };
console.log(obj.a);
obj.a accesses the value stored under the key "a", which is 10. If the key didn't exist, it would return undefined — not an error.
Use const for objects — you can still add or change properties freely; const only prevents reassigning the variable to a different object:
const user = { name: "Aman" };
user.name = "Raj"; // ✓ allowed — property updated
user.age = 22; // ✓ allowed — new property added
console.log(user);
// user = {}; // ✗ Error — cannot reassign the binding
Use the in operator to check if a property exists — more reliable than comparing with undefined:
const person = { name: "Aman", age: 22 };
console.log("name" in person); // true
console.log("salary" in person); // false
// Avoid this — a property can exist AND equal undefined
console.log(person.salary === undefined); // true — ambiguous!
Use destructuring to extract multiple properties from an object into individual variables in one line:
const person = { name: "Aman", age: 22, city: "Vadodara" };
// Old way
let name = person.name;
let age = person.age;
// Modern destructuring — one line
const { name: n, age: a, city } = person;
console.log(n, a, city);
Use Object.keys(), Object.values(), and Object.entries() to get arrays of an object's keys, values, or both:
const scores = { maths: 95, science: 88, english: 91 };
console.log(Object.keys(scores)); // ["maths", "science", "english"]
console.log(Object.values(scores)); // [95, 88, 91]
console.log(Object.entries(scores)); // [["maths",95],["science",88],...]
A property is updated and a new one is added — what does each
console.log print? Think before running.
let obj = {
name: "Aman",
age: 22
};
obj.age = 25;
obj.city = "Delhi";
console.log(obj.age);
console.log(obj.city);
// Initial object:
// obj = { name: "Aman", age: 22 }
// Step 1: obj.age = 25
// The key "age" already exists → its value is UPDATED
// obj = { name: "Aman", age: 25 }
// Step 2: obj.city = "Delhi"
// The key "city" does not yet exist → a NEW property is ADDED
// obj = { name: "Aman", age: 25, city: "Delhi" }
// Step 3: console.log(obj.age)
// age was updated from 22 to 25
// Output → 25
// Step 4: console.log(obj.city)
// city was just added
// Output → "Delhi"
// Final output:
// 25 ← updated value
// "Delhi" ← newly added property
// Key takeaway:
// Assigning to an existing key → UPDATES it
// Assigning to a new key → ADDS it
// Both work identically — no special syntax needed.