Skip to content

Beginner · Arrays and objects · topic 18 of 61 · 25 min

Objects: keys and values

Explanation

An object groups related values under names called keys (or properties), like { name: "Asha", city: "Pune" }. Read and write properties with dot or bracket notation, add methods, and list keys and values with Object.keys, Object.values and Object.entries. Objects are how JavaScript represents records such as a user, an order or a product.

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.

javascript
const order = {
  id: 'OD1023',
  customer: 'Asha',
  total: 1499,
  paid: true,
  items: ['kurta', 'dupatta'],
};
console.log(order.customer);      // 'Asha'
console.log(order['total']);      // 1499

Dot 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'].

javascript
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

javascript
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 Ravi

Checking 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.

javascript
console.log(Object.hasOwn(user, 'city'));  // true
console.log('toString' in user);           // true (inherited from Object.prototype)
console.log(Object.hasOwn(user, 'toString')); // false

Walking through an object

javascript
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".

Careful: Keys are always strings (or symbols). obj[1] and obj['1'] are the same property. And using an object as a key, obj[{}] = 1, silently uses the key "[object Object]". When you need non-string keys, use a Map (module 7).
Think of it like this: An object is like a filled-in form: each box has a printed label (the key) and your answer (the value). An array is like a numbered list on the back of the form. Real data is usually a form with lists on it, like an order with a list of items.
Tip: Object.entries + map + Object.fromEntries is the standard way to transform every value of an object.

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

Objects

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.

javascript
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}`);
Prints Steel Bottle – ₹349 – New seller.

Practice (0/3 done)

Task 1 · Code · Javascript

Write makeUser(name, age) that returns an object { name, age, isAdult } where isAdult is true when age is 18 or more.

Task 2 · Code · Javascript

Write outOfStock(stock) that returns an array of the item names whose quantity is 0, in the order they appear.

Task 3 · Code · Javascript

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

Question 1

1.const key = "city"; const o = { city: "Goa" }; Which reads "Goa"?

Question 2

2.What does Object.keys({ a: 1, b: 2 }) return?

Question 3

3.const o = {}; o[1] = "x"; What is o["1"]?

Question 4

4.Which safely reads user.address.pin when address may be missing?

Read more (free)

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.

From Prototypes and the prototype chain

In function f(...args), the three dots are called…Related

Answer: rest

In a parameter list they collect arguments: rest.

From Destructuring, spread and rest

const o = { n: 1, get() { return this.n; } }; What is o.get()?Related

Answer: 1

Called as a method, this is o.

From How this works

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

  1. 2 more topics in “Arrays and objects” before its exam: Destructuring, spread and rest, References, copies and equality.
  2. Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.

← Previous: Array methods: map, filter, reduce and friends