Reading history

JavaScript Objects: Properties, Methods, Destructuring, JSON

4 min read 2 views

Learn JavaScript objects: properties and methods, dot vs bracket notation, optional chaining, destructuring, spread, references and JSON.

An object groups related data under named keys, so one variable can describe a whole thing: a student with a name, an id and an address, or a product with a title and a price. Objects are the core building block of JavaScript; arrays, functions and the elements of a web page are all objects underneath. This lesson covers creating, reading and changing them, plus destructuring, spread and JSON.

In this lesson you will learn

  • Object literals, properties and methods
  • Dot and bracket notation
  • Adding, changing and deleting properties
  • Optional chaining ?.
  • Destructuring, spread, references and JSON

Creating and Using Objects

const student = {
  name: "Ayesha",
  id: 2101,
  subjects: ["Physics", "Math"],
  address: { city: "Chattogram", zip: "4000" },
  describe() {
    return `${this.name} (${this.id}) lives in ${this.address.city}`;
  },
};

console.log(student.name, student["id"]);
console.log(student.subjects[1], student.address.zip);
console.log(student.describe());

student.email = "ayesha@example.com";  // add a property
student.id = 2102;                     // change a property
delete student.subjects;               // remove a property
console.log(Object.keys(student));
console.log("phone" in student, student.phone);
console.log(student.address?.city, student.parent?.name);

Output

Ayesha 2101
Math 4000
Ayesha (2101) lives in Chattogram
[ 'name', 'id', 'address', 'describe', 'email' ]
false undefined
Chattogram undefined
  • An object literal is a list of key: value pairs in braces. Values can be anything, including arrays, other objects and functions.
  • Read a property with a dot, student.name, or with brackets, student["id"]. Brackets are needed when the key is stored in a variable or contains spaces.
  • A function stored in an object is a method. Inside it, this refers to the object the method was called on.
  • Assigning to a new key adds it; assigning to an existing key changes it; delete removes it.
  • A missing property reads as undefined. The in operator checks whether a key exists.
  • student.parent?.name uses optional chaining: because parent does not exist, it returns undefined instead of throwing an error.

Destructuring, Spread and JSON

const book = { title: "Learning JS", pages: 320, year: 2024 };

// Destructuring
const { title, pages } = book;
console.log(title, pages);

// Spread: copy and change
const updated = { ...book, year: 2025, edition: 2 };
console.log(updated);
console.log(book.year);   // the original is unchanged

// Loop over entries
for (const [key, value] of Object.entries(book)) {
  console.log(`${key}: ${value}`);
}

// Objects are copied by reference
const alias = book;
alias.pages = 999;
console.log(book.pages);

// JSON: convert to and from text
const text = JSON.stringify(book);
console.log(text);
console.log(JSON.parse(text).title);

Output

Learning JS 320
{ title: 'Learning JS', pages: 320, year: 2025, edition: 2 }
2024
title: Learning JS
pages: 320
year: 2024
999
{"title":"Learning JS","pages":999,"year":2024}
Learning JS
  • Destructuring, const { title, pages } = book;, creates variables from properties with the same names.
  • The spread syntax { ...book, year: 2025 } copies all properties into a new object and then overrides or adds some. The original is unchanged.
  • Object.entries() gives [key, value] pairs to loop over; Object.keys() and Object.values() give one side only.
  • Objects are stored by reference. alias and book are two names for the same object, so changing alias.pages also changes book.pages. That is why the JSON line shows 999.
  • JSON.stringify() turns an object into text for saving or sending to a server; JSON.parse() turns that text back into an object.

Arrays of Objects

Real data usually comes as an array of objects, and the array methods work on it directly:

const products = [
  { name: "Pen", price: 20 },
  { name: "Notebook", price: 80 },
  { name: "Bag", price: 950 },
];
const cheap = products.filter((p) => p.price < 100).map((p) => p.name);
console.log(cheap); // ["Pen", "Notebook"]

Common Mistakes

  1. Using a variable with dot notation: obj.key looks for a property literally named “key”. Use obj[key].
  2. Thinking = copies an object. It copies the reference; use spread for a shallow copy or structuredClone() for a deep one.
  3. Using an arrow function as a method and expecting this to be the object.
  4. Reading deep properties without checks, causing “Cannot read properties of undefined”. Use ?..

Practice Exercises

Exercise 1. Create a car object with brand, model and year, and a method age() that returns how old it is in 2026.

Show answer
const car = {
  brand: "Toyota",
  model: "Axio",
  year: 2018,
  age() {
    return 2026 - this.year;
  },
};
console.log(car.age()); // 8

Exercise 2. Count how many times each word appears in ["a", "b", "a", "c", "a"], storing the counts in an object.

Show answer
const counts = {};
for (const w of ["a", "b", "a", "c", "a"]) {
  counts[w] = (counts[w] ?? 0) + 1;
}
console.log(counts); // { a: 3, b: 1, c: 1 }

Frequently Asked Questions

What is the difference between an object and JSON?

An object is a live value in your program. JSON is a text format for data. Its keys must be in double quotes and it cannot hold functions or undefined.

How do I check if an object is empty?

Use Object.keys(obj).length === 0.

Summary

  • Objects store key-value pairs; functions inside them are methods.
  • Use dot notation for fixed names and brackets for dynamic keys.
  • Destructuring and spread make reading and copying concise.
  • Objects are shared by reference; JSON converts them to and from text.

Next: The JavaScript DOM.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *