JavaScript ยท Chapter 13 of 55

JavaScript Objects

An object is a collection of key-value pairs, called properties. Objects let you group related data and behaviour together, modeling real-world things like a 'car' or a 'user'.

You can create objects with curly-brace literal syntax, and access their properties with dot notation or bracket notation.

Creating objects

`let car = { brand: 'Toyota', year: 2020 };` creates an object with two properties. Values can be any type, including functions and other objects.

Accessing properties

Use `car.brand` (dot notation) or `car['brand']` (bracket notation, useful for dynamic keys).

Example 1 (javascript)
let car = { brand: "Toyota", year: 2020 };
console.log(car.brand);
console.log(car["year"]);
Output
Toyota
2020

Both dot and bracket notation access the same properties.

Example 2 (javascript)
let person = { name: "Sam", greet() { return "Hi " + this.name; } };
console.log(person.greet());
Output
Hi Sam

Objects can hold methods (functions as properties).

Key points

  • Objects store data as key-value pairs called properties.
  • Dot notation (`obj.key`) is the common access style.
  • Bracket notation (`obj['key']`) supports dynamic or non-identifier keys.
  • Object values can be functions, called methods.
๐Ÿ’ก Note: Objects are reference types โ€” copying a variable copies the reference, not the data.

๐Ÿ“ Quick Quiz

1. How do you create an object literal?

2. Which accesses a property dynamically by variable name?

3. A function stored as an object property is called a: