๐Ÿง  JavaScript Object Properties

๐Ÿ“Œ 1. What is an Object?

In JavaScript, an object is a collection of key-value pairs.

jsCopyEditconst person = {
  name: "Alice",
  age: 30,
  isStudent: false
};
  • name, age, and isStudent are properties.
  • The keys (like name) are property names, and the values (like "Alice") are property values.

๐Ÿ“Œ 2. Accessing Object Properties

Dot Notation

jsCopyEditconsole.log(person.name); // "Alice"

Bracket Notation

jsCopyEditconsole.log(person["age"]); // 30

Use bracket notation when:

  • The property name has spaces or special characters
  • You’re accessing properties dynamically
jsCopyEditconst prop = "isStudent";
console.log(person[prop]); // false

๐Ÿ“Œ 3. Adding or Updating Properties

Add a new property:

jsCopyEditperson.country = "USA";

Update an existing property:

jsCopyEditperson.age = 31;

๐Ÿ“Œ 4. Deleting Properties

jsCopyEditdelete person.isStudent;

๐Ÿ“Œ 5. Checking If a Property Exists

Using in operator:

jsCopyEditconsole.log("name" in person); // true

Using hasOwnProperty():

jsCopyEditconsole.log(person.hasOwnProperty("age")); // true

๐Ÿ“Œ 6. Looping Through Properties

jsCopyEditfor (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

๐Ÿ“Œ 7. Object Methods (Functions as Properties)

jsCopyEditconst car = {
  brand: "Toyota",
  start: function () {
    console.log("Engine started");
  }
};

car.start(); // "Engine started"

Shortcut (ES6):

jsCopyEditconst car = {
  brand: "Toyota",
  start() {
    console.log("Engine started");
  }
};

๐Ÿ“Œ 8. Getters and Setters

jsCopyEditconst user = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  set fullName(name) {
    const [first, last] = name.split(" ");
    this.firstName = first;
    this.lastName = last;
  }
};

console.log(user.fullName); // John Doe
user.fullName = "Jane Smith";
console.log(user.firstName); // Jane

๐Ÿ“Œ 9. Practice Task

Create an object called book with these properties:

  • title (string)
  • author (string)
  • year (number)

Add a method getSummary that returns a string summary of the book.