๐ 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
, andisStudent
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.