JavaScript Objects
Store and organize data with key-value pairs
🏠 What are JavaScript Objects?
Objects are containers that store data in key-value pairs. Think of them like a filing cabinet where each drawer has a label (key) and contents (value).
// Creating a simple object
let person = {
name: "Alice",
age: 25,
city: "New York"
};
console.log(person.name); // Access property
console.log(person.age);
console.log(person.city);
Console Output:
Alice 25 New York
Object Features
Properties
Store data with descriptive names
car.brand = "Toyota";
Methods
Functions that belong to objects
car.start = function() {...}
Dynamic
Add or remove properties anytime
car.color = "red";
Flexible
Store any type of data
obj.mixed = [1, "text", true];
🔹 Creating and Using Objects
There are different ways to create and work with objects:
// Method 1: Object literal (most common)
let student = {
name: "Bob",
grade: "A",
subjects: ["Math", "Science", "English"]
};
// Method 2: Using new Object()
let teacher = new Object();
teacher.name = "Ms. Smith";
teacher.subject = "Mathematics";
// Accessing properties
console.log(student.name); // Dot notation
console.log(student["grade"]); // Bracket notation
// Adding new properties
student.age = 16;
student["school"] = "Central High";
console.log(student);
Console Output:
Bob
A
{
name: "Bob",
grade: "A",
subjects: ["Math", "Science", "English"],
age: 16,
school: "Central High"
}
🔹 Object Methods
Objects can contain functions called methods:
let calculator = {
// Properties
brand: "Casio",
model: "FX-991",
// Methods
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
// Method using 'this' keyword
getInfo: function() {
return this.brand + " " + this.model;
}
};
// Using object methods
console.log(calculator.add(5, 3));
console.log(calculator.subtract(10, 4));
console.log(calculator.getInfo());
Console Output:
8 6 Casio FX-991
🔹 Real-World Examples
Objects are perfect for representing real-world entities:
// User profile object
let userProfile = {
username: "john_doe",
email: "[email protected]",
isActive: true,
loginCount: 42,
preferences: {
theme: "dark",
notifications: true
},
updateEmail: function(newEmail) {
this.email = newEmail;
console.log("Email updated to: " + newEmail);
}
};
// Product object
let product = {
id: 1001,
name: "Wireless Headphones",
price: 99.99,
inStock: true,
categories: ["Electronics", "Audio"],
applyDiscount: function(percentage) {
this.price = this.price * (1 - percentage / 100);
return this.price;
}
};
// Using the objects
userProfile.updateEmail("[email protected]");
console.log("New price:", product.applyDiscount(20));
Console Output:
Email updated to: [email protected] New price: 79.992