Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 07

Day 7: Objects, Destructuring, Spread & JSON

⏱ 90 min📶 Beginner🎯 100% self-study
Day 7 / 30

✅ Today you will learn

  • Model real things with key: value pairs
  • Dot vs bracket access, add/update/delete properties
  • Methods and a first look at this
  • Object.keys / values / entries, destructuring, spread
  • Arrays of objects and JSON – the language of APIs

🏢 In the real world

A product is not one value – it has a name, a price, a category, stock and a rating. An order has a customer, items and a total. Real apps (and every API on the internet) represent data as objects and arrays of objects. After today you can read any JSON response a backend developer sends you.

Creating and reading objects

JavaScript
const product = {
  id: 1,
  name: 'Kaju Katli',
  price: 900,
  category: 'dry',
  inStock: true,
  'shelf life': '15 days',        // keys with spaces need quotes
};

console.log(product.name, product.price);      // dot access
console.log(product['shelf life']);            // bracket access
const field = 'category';
console.log(product[field]);                   // dynamic key → brackets
console.log(product.discount);                 // missing → undefined
Kaju Katli 900 15 days dry undefined

Add, update, delete, check

JavaScript
const order = { id: 1042, customer: 'Aarti', total: 1800 };
order.status = 'packing';        // add
order.total = 1890;              // update
delete order.customer;           // delete
console.log(order);
console.log('status' in order, Object.hasOwn(order, 'customer'));

const settings = Object.freeze({ gst: 5 });   // lock an object
settings.gst = 18;                            // silently ignored (error in strict mode)
console.log(settings.gst);
{ id: 1042, total: 1890, status: 'packing' } true false 5

Methods and this

JavaScript
const cartLine = {
  name: 'Ghewar',
  price: 650,
  qty: 2,
  total() {                      // a method = function inside an object
    return this.price * this.qty;   // this = the object the method was called on
  },
  label() {
    return `${this.qty} × ${this.name} = ₹${this.total()}`;
  },
};
console.log(cartLine.total());
console.log(cartLine.label());
1300 2 × Ghewar = ₹1300
⚠️ Arrow functions as methods

Do not write total: () => this.price * this.qty. Arrow functions have no own this, so this.price is undefined. Use the method shorthand total() { … }. Day 17 explains this fully.

Looping over objects

JavaScript
const stock = { kaju: 25, ghewar: 8, rasmalai: 12, kalakand: 0 };

console.log(Object.keys(stock));
console.log(Object.values(stock));
for (const [item, kg] of Object.entries(stock)) {
  console.log(`${item.padEnd(9)} ${kg > 0 ? kg + ' kg' : 'OUT OF STOCK'}`);
}
const totalKg = Object.values(stock).reduce((sum, kg) => sum + kg, 0);
console.log('Total stock:', totalKg, 'kg');
[ 'kaju', 'ghewar', 'rasmalai', 'kalakand' ] [ 25, 8, 12, 0 ] kaju 25 kg ghewar 8 kg rasmalai 12 kg kalakand OUT OF STOCK Total stock: 45 kg

Destructuring and spread

JavaScript
const customer = { name: 'Riya', phone: '9829012345', address: { city: 'Jaipur', pin: '302003' } };

const { name, phone } = customer;                       // pull out properties
const { address: { city } } = customer;                 // nested
const { email = 'not given' } = customer;               // default value
console.log(name, phone, city, email);

const [firstSweet, , thirdSweet] = ['Kaju', 'Ghewar', 'Ladoo'];   // array destructuring
console.log(firstSweet, thirdSweet);

const updated = { ...customer, phone: '9876543210' };   // copy + override
console.log(customer.phone, '→', updated.phone);

function printLabel({ name, address: { pin } }) {        // destructure parameters
  return `${name} – PIN ${pin}`;
}
console.log(printLabel(customer));
Riya 9829012345 Jaipur not given Kaju Ladoo 9829012345 → 9876543210 Riya – PIN 302003
🧠 Spread is shallow

{ ...customer } copies the top level only; updated.address is still the same object as customer.address. Use structuredClone(customer) for a full deep copy.

Arrays of objects – real data

JavaScript
const orders = [
  { id: 1041, customer: 'Aarti', city: 'Jaipur', total: 1800, paid: true },
  { id: 1042, customer: 'Rahul', city: 'Ajmer',  total: 650,  paid: false },
  { id: 1043, customer: 'Sana',  city: 'Jaipur', total: 2400, paid: true },
];
let revenue = 0, unpaid = [];
for (const o of orders) {
  if (o.paid) revenue += o.total;
  else unpaid.push(o.customer);
}
console.log('Revenue collected: ₹' + revenue);
console.log('Remind:', unpaid.join(', '));
console.table(orders.map(({ id, customer, total }) => ({ id, customer, total })));
Revenue collected: ₹4200 Remind: Rahul ┌─────────┬──────┬──────────┬───────┐ │ (index) │ id │ customer │ total │ ├─────────┼──────┼──────────┼───────┤ │ 0 │ 1041 │ 'Aarti' │ 1800 │ │ 1 │ 1042 │ 'Rahul' │ 650 │ │ 2 │ 1043 │ 'Sana' │ 2400 │ └─────────┴──────┴──────────┴───────┘

JSON – how data travels

JavaScript
const order = { id: 1043, items: [{ name: 'Rasmalai', qty: 2 }], paid: true };

const text = JSON.stringify(order);            // object → JSON string (to send/save)
console.log(text, typeof text);

const back = JSON.parse(text);                 // JSON string → object (received)
console.log(back.items[0].name, typeof back);

console.log(JSON.stringify(order, null, 2));   // pretty print with 2 spaces
{"id":1043,"items":[{"name":"Rasmalai","qty":2}],"paid":true} string Rasmalai object { "id": 1043, "items": [ { "name": "Rasmalai", "qty": 2 } ], "paid": true }
JSON ruleExample
Keys always in double quotes{"name": "Ghewar"}
Strings in double quotes only"Jaipur" (not 'Jaipur')
Allowed valuesstring, number, true/false, null, object, array
Not allowedfunctions, undefined, comments, trailing commas
DatesStored as strings: "2026-10-25T10:30:00Z"

Real task: a product card from an object

HTML + JavaScript
<div id="card"></div>

<script>
const product = { name: 'Malai Ghewar', price: 650, unit: 'kg', rating: 4.7, stock: 8, image: 'images/ghewar-400.webp' };

function productCard({ name, price, unit, rating, stock, image }) {
  const stockText = stock === 0 ? '❌ Out of stock' : stock < 10 ? `⚠️ Only ${stock} left` : '✅ In stock';
  return `
    <article style="width:220px;border:1px solid #eee;border-radius:12px;overflow:hidden">
      <img src="${image}" alt="${name}" style="width:100%;display:block">
      <div style="padding:10px">
        <b>${name}</b> <small>★ ${rating}</small><br>
        ₹${price}/${unit}<br><small>${stockText}</small>
      </div>
    </article>`;
}
document.querySelector('#card').innerHTML = productCard(product);
</script>
▶  Destructured parameters + template literal → HTML

🏅 Job skills unlocked today

✔ Model data as objects with properties and methods✔ Access, add, update and delete properties✔ Loop with Object.keys/values/entries; destructure and spread✔ Work with arrays of objects and JSON

Practice tasks

🏋️ Practice – do it yourself

Task 1: Create a student object with name, roll, marks {maths, science, english} and a method average(). Print “Riya (Roll 12): 84.3”.
Show solution
JavaScript
const student = {
  name: 'Riya', roll: 12,
  marks: { maths: 88, science: 92, english: 73 },
  average() {
    const values = Object.values(this.marks);
    let sum = 0;
    for (const m of values) sum += m;
    return Math.round(sum / values.length * 10) / 10;
  },
};
console.log(`${student.name} (Roll ${student.roll}): ${student.average()}`);
Riya (Roll 12): 84.3
Task 2: Parse this JSON and print each item line: {"orderId":"SS1","items":[{"name":"Ladoo","qty":2,"price":500},{"name":"Kaju Katli","qty":1,"price":900}]}
Show solution
JavaScript
const json = '{"orderId":"SS1","items":[{"name":"Ladoo","qty":2,"price":500},{"name":"Kaju Katli","qty":1,"price":900}]}';
const order = JSON.parse(json);
let total = 0;
for (const { name, qty, price } of order.items) {
  console.log(`${name}: ${qty} × ₹${price} = ₹${qty * price}`);
  total += qty * price;
}
console.log(`${order.orderId} total ₹${total}`);
Ladoo: 2 × ₹500 = ₹1000 Kaju Katli: 1 × ₹900 = ₹900 SS1 total ₹1900
Task 3: Make an object of 5 PIN codes → delivery charge and look up the charge for a typed PIN.

Quick quiz

🧠 Quick Quiz – test yourself

1. Access a key stored in a variable k:
Brackets evaluate the variable.
2. JSON.parse turns…
stringify is the reverse.
3. const { a = 5 } = {} gives a =
Default when missing.
4. Which is NOT valid JSON?
Single quotes not allowed.
5. Object.entries returns…
Great with for…of.

Interview corner

💼 Interview Corner

How do you deep-copy an object?

structuredClone(obj) (modern, handles dates, maps, nested objects); JSON.parse(JSON.stringify(obj)) works only for plain JSON-safe data and loses functions, undefined and dates. Spread/Object.assign are shallow.

What is destructuring and why is it useful?

Syntax to unpack properties or array items into variables (with renaming and defaults). It makes function parameters self-documenting, reduces repetition and is used everywhere in React (props, hooks).

Summary

  • Objects hold key: value pairs; dot for fixed keys, brackets for dynamic keys.
  • Methods use this; avoid arrow functions as methods.
  • Object.keys/values/entries, destructuring and spread are daily tools.
  • JSON.stringify to send, JSON.parse to receive.
➡️ Next

Day 8: map, filter, reduce, find and sort – the array superpowers behind every cart and report.

Frequently Asked Questions

Object or Map?
Use plain objects for fixed-shape records (a product). Use Map when keys are dynamic, not strings, or you add/remove many keys often.
What is console.table?
A DevTools/Node helper that prints arrays of objects as a table – great for debugging API data.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 8: map, filter, reduce, find & sort Your progress: 7 / 30 (23%) · Lesson 8 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free