JavaScript Objects
Understanding JavaScript objects and their properties
🎯 What are JavaScript Objects?
JavaScript objects are containers for named values called properties and methods. They are like real-world objects with characteristics and actions.
// Creating a simple object
let person = {
name: "John",
age: 25,
city: "New York"
};
console.log(person.name); // Output: John
Output:
John
Object Concepts
Properties
Values stored in objects
car.color = "red";
Methods
Functions inside objects
car.start = function() {
return "Engine started!";
};
Keys
Names of object properties
Object.keys(person);
Values
Data stored in properties
Object.values(person);
🔹 Creating Objects
There are several ways to create objects in JavaScript:
// Method 1: Object literal
let student = {
name: "Alice",
grade: "A",
subjects: ["Math", "Science"]
};
// Method 2: Using new Object()
let teacher = new Object();
teacher.name = "Mr. Smith";
teacher.subject = "History";
// Method 3: Constructor function
function Book(title, author) {
this.title = title;
this.author = author;
}
let myBook = new Book("JavaScript Guide", "John Doe");
Output:
student: {name: "Alice", grade: "A", subjects: Array(2)}
teacher: {name: "Mr. Smith", subject: "History"}
myBook: {title: "JavaScript Guide", author: "John Doe"}
🔹 Accessing Object Properties
You can access object properties using dot notation or bracket notation:
let car = {
brand: "Toyota",
model: "Camry",
year: 2022,
"fuel-type": "gasoline"
};
// Dot notation
console.log(car.brand); // Toyota
console.log(car.model); // Camry
// Bracket notation
console.log(car["year"]); // 2022
console.log(car["fuel-type"]); // gasoline
// Dynamic property access
let property = "brand";
console.log(car[property]); // Toyota
Output:
Toyota
Camry
2022
gasoline
Toyota
🔹 Object Methods
Objects can contain functions called methods:
let calculator = {
x: 10,
y: 5,
// Method to add numbers
add: function() {
return this.x + this.y;
},
// Method to multiply numbers
multiply: function() {
return this.x * this.y;
},
// Method with parameters
divide: function(a, b) {
return a / b;
}
};
console.log(calculator.add()); // 15
console.log(calculator.multiply()); // 50
console.log(calculator.divide(20, 4)); // 5
Output:
15
50
5
🔹 Common Object Operations
Useful operations you can perform on objects:
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Adding new properties
person.email = "[email protected]";
person["phone"] = "123-456-7890";
// Modifying existing properties
person.age = 31;
// Deleting properties
delete person.phone;
// Check if property exists
console.log("email" in person); // true
console.log(person.hasOwnProperty("age")); // true
// Get all keys
console.log(Object.keys(person)); // ["firstName", "lastName", "age", "email"]
// Get all values
console.log(Object.values(person)); // ["John", "Doe", 31, "[email protected]"]
Output:
true
true
["firstName", "lastName", "age", "email"]
["John", "Doe", 31, "[email protected]"]