Curriculum / Fundamentals / Lesson 10

Objects in JavaScript

Object literals, properties, methods, and the `this` keyword basics.

10 of 30
beginner 📖 7 min read 🎯 4 questions

What is an Object?

An object is a collection of key-value pairs. Unlike arrays which are ordered lists, objects are unordered collections that you access by name (the key).

💡 Real-world analogy Think of an object like a real-world object — a person has a name, age, and can walk. In JavaScript, an object can have properties (name, age) and methods (walk).

Creating Objects

// Object literal (preferred)
let person = {
  name: "Alice",
  age: 25,
  city: "New York"
};

// Using the Object constructor
let car = new Object();
car.make = "Toyota";
car.model = "Camry";

Accessing Properties

Two ways: dot notation or bracket notation.

let person = { name: "Alice", age: 25 };

// Dot notation
console.log(person.name); // "Alice"

// Bracket notation (useful for dynamic keys)
console.log(person["age"]); // 25

// Adding new properties
person.city = "New York";

Object Methods

A method is a function that belongs to an object.

let person = {
  name: "Alice",
  age: 25,
  greet: function() {
    console.log("Hello, I'm " + this.name);
  }
};

person.greet(); // "Hello, I'm Alice"

The this Keyword

this refers to the object that the method belongs to. It's one of the most important concepts in JavaScript.

let person = {
  name: "Alice",
  introduce: function() {
    return "My name is " + this.name;
  }
};

console.log(person.introduce()); // "My name is Alice"

Common Mistakes

Quick Quiz

1. How do you access the name property of an object person?

2. What does this refer to in an object method?

3. What is a method in an object?

Summary

Back to curriculum