Chapter 10 of 28 · JavaScript for Beginners — Complete Free Tutorial

Objects & JSON

Objects are collections of key: value pairs — the shape of nearly every real-world record: a user, a product, a config, an API response. This chapter covers creating and reading objects, methods, destructuring, copying, and the JSON format that moves objects across networks.

Creating and accessing

const user = {
  name: 'Asha',
  role: 'admin',
  'join year': 2024,     // keys with spaces need quotes
  42: 'numeric key',     // becomes the string '42'
};

console.log(user.name);            // → Asha (dot notation)
console.log(user['join year']);    // → 2024 (bracket — required for odd keys)

const prop = 'role';
console.log(user[prop]);           // → admin (dynamic key)

Dot for fixed names, brackets for computed names. Missing keys return undefined, not an error.

Adding and removing

user.email = 'asha@example.com';   // add / overwrite
user['active'] = true;
delete user[42];                   // remove a key
console.log(Object.hasOwn(user, 'email'));  // → true

Shorthand and computed keys

const name = 'Kai';
const age = 30;

const profile = {
  name,                     // shorthand for name: name
  age,
  [`tag_${name}`]: 'vip',   // computed key → tag_Kai: 'vip'
};

console.log(profile);   // → { name: 'Kai', age: 30, tag_Kai: 'vip' }

Methods and this

const counter = {
  count: 0,
  increment() {            // method shorthand
    this.count++;
  },
  show() {
    return `Count: ${this.count}`;
  },
};

counter.increment();
console.log(counter.show());   // → Count: 1

this refers to the object that called the method. Arrow functions do not bind their own this — the full story is in The this Keyword.

Destructuring

const product = { title: 'Keyboard', price: 49, stock: 7 };

const { title, price } = product;
console.log(title, price);          // → Keyboard 49

const { price: cost, stock = 0 } = product;   // rename + default
console.log(cost);                  // → 49

Defaults apply to undefined only — a present 0 or '' is kept (useful pairing with ?? habits).

Nested access and optional chaining

const order = { customer: { address: { city: 'Pune' } } };

console.log(order.customer.address.city);        // → Pune
console.log(order.customer?.phone);              // → undefined (no throw)
console.log(order.shipping?.courier ?? 'pickup'); // → pickup

?. stops the chain when an intermediate value is null/undefined; ?? supplies the fallback. Together they replace defensive && chains.

Object utilities

const task = { id: 1, title: 'Ship', done: false };

console.log(Object.keys(task));      // → ['id', 'title', 'done']
console.log(Object.values(task));    // → [1, 'Ship', false]
console.log(Object.entries(task));   // → [['id', 1], ['title', 'Ship'], ['done', false]]

const copy = { ...task };            // shallow clone
const done = { ...task, done: true }; // copy + override

for (const [k, v] of Object.entries(task)) {
  console.log(`${k}=${v}`);
}

Copying: shallow vs deep

const original = { meta: { views: 1 }, tag: 'a' };

const shallow = { ...original };
shallow.meta.views = 99;
console.log(original.meta.views);   // → 99 😱 shared reference!

const deep = structuredClone(original);
deep.meta.views = 42;
console.log(original.meta.views);   // → 99 unchanged ✅

Spread copies only the top level — nested objects stay shared. For true isolation use structuredClone() (modern, handles dates/maps), or JSON.parse(JSON.stringify(x)) for plain JSON-safe data (it drops functions, undefined, dates become strings).

Arrays of objects (the real-world shape)

const products = [
  { name: 'Mouse', price: 15 },
  { name: 'Hub', price: 25 },
];

const names = products.map((p) => p.name);            // → ['Mouse', 'Hub']
const cheap = products.filter((p) => p.price < 20);    // → [Mouse]

JSON: objects over the wire

JSON (JavaScript Object Notation) is a text format: double-quoted keys, no functions, no comments — understood by every language.

const user = { name: 'Asha', tags: ['admin'] };

const text = JSON.stringify(user);       // object → string
console.log(text);
// → {"name":"Asha","tags":["admin"]}

const back = JSON.parse(text);           // string → object
console.log(back.name);                  // → Asha ✅
  • JSON.stringify(value, null, 2) pretty-prints with indentation.
  • Only JSON-safe data survives: no functions, undefined, symbols, or circular references (throws).
  • This is exactly what fetch sends and receives in chapter 22, and what browser storage requires in chapter 25.

Common mistakes

  • Bracket vs dot confusion — user['name'] is fine, but obj.a-b is subtraction, not a key; use brackets for computed or odd keys.
  • Shallow-copy surprise — {...obj} shares nested objects; reach for structuredClone.
  • JSON.stringify on functions/dates — functions vanish, dates become ISO strings (revive with new Date()).
  • Using objects where a Map fits — need arbitrary keys or guaranteed insertion order with frequent add/delete → Map.
  • Comparing objects with === — reference equality only; two structurally identical objects differ.

Practice checklist

  1. Build a getFullName({ first, last }) using destructuring with a default for last.
  2. Clone a nested object, mutate the clone, and prove the original is untouched with structuredClone.
  3. Round-trip an object through JSON.stringify → JSON.parse; delete a key in between.
  4. Convert Object.entries output into a query string: ?a=1&b=2.

Strings are objects too — with a huge method toolbox. Next: Strings & Template Literals.

Quiz: Objects & JSON

5 questions · 70% to pass

Frequently Asked Questions

JavaScript is the programming language of the web. It adds behaviour to pages: responding to clicks and input, validating forms, fetching data from APIs, updating the DOM without reloading, and much more. It also runs on servers (Node.js), in desktop and mobile apps, and in build tooling.

They are unrelated languages that share a similar name for historical marketing reasons. Java is a statically-typed compiled language; JavaScript is a dynamically-typed interpreted language designed for the browser. Knowing one does not imply knowledge of the other.

Helpful but not mandatory — HTML gives you the structure JavaScript manipulates and CSS the styling it toggles. If you know basic tags, classes and selectors, you have enough to start; the DOM chapters assume only that much.

Use const by default and let when the value must change. Avoid var entirely in modern code: it is function-scoped instead of block-scoped, hoists differently, and can create accidental globals. This course uses const and let throughout.

The Document Object Model is the browser’s in-memory tree of objects representing your HTML. JavaScript reads and modifies that tree — selecting elements, changing text, adding nodes, attaching event listeners — and the browser re-renders the page to match.

== compares after converting types (so 5 == "5" is true), while === requires the same value AND the same type (5 === "5" is false). Loose equality has famously confusing rules — use === and !== everywhere unless you have a specific reason not to.

JavaScript is single-threaded, so long-running work (timers, fetches, events) is handled by the browser and its callbacks are queued. The event loop moves queued callbacks onto the call stack only when it is empty, with promise callbacks (microtasks) taking priority over timers. It is why asynchronous code never freezes the page.

A Promise is an object representing a future value — pending, fulfilled or rejected — that can be chained and combined (Promise.all). async/await is syntax sugar over promises that lets asynchronous code read top-to-bottom with ordinary try/catch error handling.

Yes. Frameworks are built on exactly these fundamentals — components are functions, state is your variable discipline, effects are events, rendering is DOM work. Developers who learn vanilla first understand what the framework is doing and debug far faster.

Type out the examples instead of copying, build small end-to-end projects (expense tracker, weather app, quiz), handle every UI state (loading, empty, success, error), and revisit fundamentals while reading real code. Consistency beats volume — a little most days outpaces occasional marathons.