Beginner · Arrays and objects · topic 18 of 61 · 25 min
Objects: keys and values
Explanation
Why objects?
An array is good for a list of similar things. But one order has many different facts: an id, a customer, items, a total, a status. Keeping them in separate variables gets messy. An object keeps them together, each under a meaningful name.
const order = {
id: 'OD1023',
customer: 'Asha',
total: 1499,
paid: true,
items: ['kurta', 'dupatta'],
};
console.log(order.customer); // 'Asha'
console.log(order['total']); // 1499Dot versus bracket notation
Use the dot when you know the key name while writing the code: order.total. Use brackets when the key is in a variable, comes from data, or is not a valid identifier (has a space or a dash): order[field], headers['content-type'].
const field = 'status';
order[field] = 'SHIPPED'; // adds a new property named status
order.total = 1299; // changes an existing one
delete order.paid; // removes a property
console.log(order.discount); // undefined (missing keys give undefined)Shorthand, computed keys and methods
const name = 'Ravi';
const city = 'Chennai';
const key = 'mobile';
const user = {
name, // shorthand for name: name
city,
[key]: '98xxxxxx21', // computed key: the value of key becomes the name
greet() { // a method: a function stored in the object
return `Hi, I am ${this.name}`;
},
};
console.log(user.mobile, user.greet()); // 98xxxxxx21 Hi, I am RaviChecking whether a key exists
user.age === undefined cannot tell "missing" from "present but undefined". Use Object.hasOwn(obj, key) (ES2022) to check the object's own keys, or the in operator, which also looks at inherited keys.
console.log(Object.hasOwn(user, 'city')); // true
console.log('toString' in user); // true (inherited from Object.prototype)
console.log(Object.hasOwn(user, 'toString')); // falseWalking through an object
const stock = { rice: 40, dal: 25, oil: 0 };
console.log(Object.keys(stock)); // ['rice', 'dal', 'oil']
console.log(Object.values(stock)); // [40, 25, 0]
for (const [item, qty] of Object.entries(stock)) {
if (qty === 0) console.log('Restock', item); // Restock oil
}
const doubled = Object.fromEntries(
Object.entries(stock).map(([k, v]) => [k, v * 2])
);
console.log(doubled); // { rice: 80, dal: 50, oil: 0 }Nested objects and optional chaining
Objects can hold other objects and arrays: order.address.pin. If a level might be missing, use ?. so the code gives undefined instead of crashing with "Cannot read properties of undefined".
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Objects: keys and values · 1/7
In this lesson you will group related values into objects.
Prefer a video by a teacher? Find free videos on “javascript objects properties methods Object.entries tutorial” on YouTube ↗
In real life: A product card on a shopping app
Every product on a shopping app is an object from the server. The app reads nested fields like seller.rating with optional chaining, because some products come without a seller rating yet.
const product = { id: 77, title: 'Steel Bottle', price: 349, seller: { name: 'HomeKart' } };
const rating = product.seller?.rating ?? 'New seller';
console.log(`${product.title} – ₹${product.price} – ${rating}`);Practice (0/3 done)
Write makeUser(name, age) that returns an object { name, age, isAdult } where isAdult is true when age is 18 or more.
Write outOfStock(stock) that returns an array of the item names whose quantity is 0, in the order they appear.
Write applyPriceRise(prices, percent) that returns a NEW object with every price increased by percent and rounded to the nearest rupee. The original object must not change.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Destructuring, spread and restArrays and objects · same module
- Arrays: lists of valuesArrays and objects · same module
- Objects in depthFrontend Web Development · JavaScript in depth
- Prototypes and the prototype chainScope, this, prototypes and classes
- How this worksScope, this, prototypes and classes
- Typing functions and objectsFrontend Web Development · TypeScript basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
const key = "city"; const o = { city: "Goa" }; Which reads "Goa"?
Answer: o[key]
Brackets use the VALUE of the variable key, which is "city".
What does Object.keys({ a: 1, b: 2 }) return?
Answer: ['a', 'b']
Object.keys gives the property names.
const o = {}; o[1] = "x"; What is o["1"]?
Answer: "x"
Object keys are strings, so 1 and "1" are the same key.
Which safely reads user.address.pin when address may be missing?
Answer: user.address?.pin
?. after address stops the read if address is null or undefined.
const user = { name: 'Asha' }; What is user.address?.city?Related
Answer: undefined
user.address is undefined, so ?. stops there and gives undefined instead of throwing an error.
From Objects in depth
const p = { x: 1 }; const c = Object.create(p); c.x = 2; What is p.x?Related
Answer: 1
Writing c.x creates an own property on c that shadows p.x; p is unchanged.
In function f(...args), the three dots are called…Related
const o = { n: 1, get() { return this.n; } }; What is o.get()?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Arrays and objects” before its exam: Destructuring, spread and rest, References, copies and equality.
- Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.