Object basics
Overview
An object groups related values under named keys (also called properties). Where a variable holds one value, an object holds a whole bundle of them — everything about a course, a user or a product, in one place.
const course = {
title: 'JavaScript Essentials',
chapters: 14,
published: true,
};The curly braces create an object literal. Inside, each property is written as key: value, separated by commas. A comma after the last property (a “trailing comma”) is allowed and makes adding new lines tidier.
Values can be anything: strings, numbers, arrays, other objects, even functions.
const user = {
name: 'Asha',
roles: ['learner', 'editor'],
address: { city: 'Pune', pin: '411001' },
greet() {
return `Hi, I'm ${this.name}`;
},
};
user.address.city; // 'Pune'
user.roles[1]; // 'editor'
user.greet(); // "Hi, I'm Asha"Reading and writing
course.title; // 'JavaScript Essentials'
course['chapters']; // 14
const key = 'published';
course[key]; // true — brackets work with a variable
course.level = 'Beginner'; // add a property
course.chapters = 15; // change one
delete course.published; // remove oneReading a key that doesn’t exist gives undefined, not an error. But reading a property of undefined does throw — that’s what optional chaining (?.) is for:
course.author; // undefined
course.author.name; // TypeError: Cannot read properties of undefined
course.author?.name; // undefinedDot or brackets?
| Use dot notation… | Use brackets… |
|---|---|
| when you know the key while writing the code | when the key is in a variable: obj[key] |
for normal names: user.name |
for keys with spaces or dashes: obj['first-name'] |
| most of the time | for computed keys: obj['item' + i] |
Keys are strings
Object keys are always strings (or symbols). Numbers used as keys are converted: obj[1] and obj['1'] are the same property. Keys that aren’t valid variable names must be quoted in the literal:
const headers = {
'Content-Type': 'application/json',
'x-request-id': 'abc123',
};Shorthand
When a variable has the same name as the key, write it once:
const title = 'SQL';
const level = 'Beginner';
const course2 = { title, level }; // { title: 'SQL', level: 'Beginner' }Computed keys
Put an expression in square brackets to calculate a key while creating the object:
const field = 'email';
const errors = {
[field]: 'Required', // { email: 'Required' }
[`${field}Length`]: 0, // { emailLength: 0 }
};Checking for keys
Because missing keys give undefined, checking obj.key === undefined can’t tell “missing” from “set to undefined”. Use one of these instead:
'title' in course; // true — also finds inherited properties
Object.hasOwn(course, 'title'); // true — only the object's own propertiesLooping over objects
Object.keys(course); // ['title', 'chapters', 'level']
Object.values(course); // ['JavaScript Essentials', 15, 'Beginner']
Object.entries(course); // [['title', 'JavaScript Essentials'], ['chapters', 15], …]
for (const [key, value] of Object.entries(course)) {
console.log(`${key}: ${value}`);
}Turning an object into arrays unlocks every array method:
const prices = { tea: 20, coffee: 35, cake: 60 };
const total = Object.values(prices).reduce((sum, p) => sum + p, 0); // 115
const cheap = Object.entries(prices).filter(([, p]) => p < 50); // [['tea', 20], ['coffee', 35]]Object.fromEntries goes the other way, turning [key, value] pairs back into an object:
const doubled = Object.fromEntries(
Object.entries(prices).map(([item, p]) => [item, p * 2]),
);
// { tea: 40, coffee: 70, cake: 120 }Property order
Properties keep the order they were added in, with one exception: keys that look like whole numbers ('1', '42') come first, in numeric order. If order matters a lot, use an array or a Map.
Objects as lookup tables
Objects make great dictionaries — you look a value up by its key instead of searching:
const capitals = { India: 'New Delhi', Japan: 'Tokyo', Kenya: 'Nairobi' };
capitals['Japan']; // 'Tokyo'The exercise uses this idea to count words: each word is a key, and its count is the value.
Objects are references
A variable doesn’t contain an object; it holds a reference to it. Copying the variable copies the reference, so both names point at the same object:
const a = { score: 1 };
const b = a;
b.score = 99;
console.log(a.score); // 99Likewise, two separately created objects are never equal, even with the same contents: { x: 1 } === { x: 1 } is false. The Spread and copying topic shows how to make real copies.
constobjects can still change.conststops you pointing the name at a different object, but you can still edit its properties.
Count the words
Write countWords(text) that returns an object with how often each word appears: countWords('a b a') → { a: 2, b: 1 }. Make it ignore upper/lower case.
function countWords(text) {
// your code here
}
countWords('The cat and the hat'); // { the: 2, cat: 1, and: 1, hat: 1 }function countWords(text) {
const counts = {};
for (const word of text.toLowerCase().split(' ')) {
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}Summary
- Objects store values under named keys (properties); values can be any type, including other objects and functions.
- Use dot notation for fixed names and brackets for names held in a variable or with special characters.
- Reading a missing key gives
undefined; useinorObject.hasOwnto check whether a key exists. Object.keys,Object.valuesandObject.entriesturn an object into arrays you can loop over.- Objects are stored by reference: copying the variable doesn’t copy the object.