An object groups related values under names. Where an array is a numbered list, an object is a set of labelled things, like a user profile: name, age, email.
const user = {
name: "Maya",
age: 28,
isAdmin: false,
languages: ["English", "Hindi"]
};
console.log(user.name); // → Maya
console.log(user.languages[1]); // → Hindi
Curly braces create the object. Inside are properties, each a key: value pair, separated by commas. A value can be anything: text, numbers, arrays, other objects, even functions.
Realistic objects
Objects model real things. Here are the kinds you will see again and again:
const product = { id: 7, name: "Notebook", price: 4.5, inStock: true };
const post = {
title: "Learning JavaScript",
author: { name: "Deepak", id: 1 },
tags: ["js", "beginner"]
};
const settings = { theme: "dark", fontSize: 16, notifications: { email: true, push: false } };
console.log(post.author.name); // → Deepak
console.log(settings.notifications.email); // → true
Property shorthand
When the variable has the same name as the key, write it once.
const name = "Maya";
const age = 28;
const user = { name, age }; // same as { name: name, age: age }
console.log(user); // → { name: Maya, age: 28 }
Objects are references
A variable holds a reference to the object, not a copy. Two names can point at one object.
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // → 2
console.log(a === b); // → true
That is why const objects can still be changed, and why you need to copy objects deliberately: Copying Objects.
Other ways to create objects
You will meet them later: new Object() (rarely used), Object.create() (prototypes), constructor functions and classes.
Objects vs arrays
users). Use an object for one thing with named parts (user). Often you combine them: an array of objects.