JavaScript Intermediate Day 3: Objects Deep Dive

Goal of this Day

Today you will learn:

By the end, you will be able to work efficiently with objects and their methods.

Step 1: Object Methods

Objects can contain functions as methods:


const user = {
  name: "John",
  greet() {
    return "Hello " + this.name;
  }
};

console.log(user.greet()); // Hello John

Explanation:

Step 2: Destructuring

Destructuring allows you to extract properties easily:


const user = {
  name: "John",
  age: 25
};

const { name, age } = user;
console.log(name); // John
console.log(age);  // 25

Practice


const user = {
  name: "John",
  greet() {
    return "Hello " + this.name;
  }
};

console.log(user.greet());

Task

Complete the following:

Example:


const person = {
  name: "Alice",
  age: 30,
  sayHi() {
    return "Hi, I am " + this.name;
  }
};

// Call the method
console.log(person.sayHi()); // Hi, I am Alice

// Destructuring
const { name, age } = person;
console.log(name); // Alice
console.log(age);  // 30