Objects
In JavaScript, objects are used to store multiple pieces of related data and functionality. Think of an object as a collection of key-value pairs, where each key is a property (or method), and each value holds the data or function for that property.
What is an Object?
An object is like a real-world object. For example:
- A car has properties like color and model and methods like drive and stop.
- A person has properties like name and age and methods like speak.
Example: Simple Object
let person = { name: "Alice", // Property age: 25, // Property speak: function () { // Method console.log("Hello!"); } }; console.log(person.name); // Outputs: Alice person.speak(); // Outputs: Hello!
How to Create an Object
a) Object Literal
This is the easiest and most common way to create an object.
let car = { brand: "Toyota", color: "Red", start: function () { console.log("Car is starting..."); } };
b) Using the new Object() Syntax
You can also create an object using the Object constructor.
let person = new Object(); person.name = "Bob"; person.age = 30; console.log(person.name); // Outputs: Bob
Accessing Object Properties
You can access properties in two ways:- Dot Notation: objectName.propertyName
- Bracket Notation: objectName["propertyName"]
Example:
let book = { title: "The Alchemist", author: "Paulo Coelho" }; console.log(book.title); // Dot notation: Outputs: The Alchemist console.log(book["author"]); // Bracket notation: Outputs: Paulo Coelho
Adding and Modifying Properties
You can add or modify properties directly using dot or bracket notation.
Example:
let laptop = { brand: "Dell" }; // Adding a new property laptop.model = "XPS 13"; // Modifying an existing property laptop.brand = "HP"; console.log(laptop); // Outputs: { brand: "HP", model: "XPS 13" }
Removing Properties
Use the delete keyword to remove a property.
Example:
let user = { name: "Emma", age: 28 }; delete user.age; console.log(user); // Outputs: { name: "Emma" }
Methods in Objects
A method is a function inside an object.
Example:
let calculator = { add: function (a, b) { return a + b; }, subtract: function (a, b) { return a - b; } }; console.log(calculator.add(5, 3)); // Outputs: 8 console.log(calculator.subtract(10, 4)); // Outputs: 6
Looping Through Object Properties
Use the for...in loop to iterate through all properties of an object.
Example:
let person = { name: "Sophia", age: 22, country: "USA" }; for (let key in person) { console.log(key + ": " + person[key]); } // Outputs: // name: Sophia // age: 22 // country: USA
Object Methods
a) Object.keys()
Returns an array of the object's keys.
let person = { name: "Sophia", age: 22, country: "USA" }; for (let key in person) { console.log(key + ": " + person[key]); } // Outputs: // name: Sophia // age: 22 // country: USA
b) Object.values()
Returns an array of the object's values.
console.log(Object.values(car)); // Outputs: ["Ford", "Mustang"]
c) Object.entries()
Returns an array of key-value pairs.
console.log(Object.entries(car)); // Outputs: [["brand", "Ford"], ["model", "Mustang"]]
Nested Objects
Objects can contain other objects.
Example:let student = { name: "Alex", grades: { math: 90, science: 85 } }; console.log(student.grades.math); // Outputs: 90
this Keyword in Objects
The this keyword refers to the current object.
let person = { name: "John", greet: function () { console.log("Hello, my name is " + this.name); } }; person.greet(); // Outputs: Hello, my name is John
Example Program: Student Object
Here's a simple program using an object to manage a student's information.
let student = { name: "Maria", grades: [80, 85, 90], addGrade: function (grade) { this.grades.push(grade); }, calculateAverage: function () { let total = 0; for (let grade of this.grades) { total += grade; } return total / this.grades.length; } }; student.addGrade(95); console.log(student.calculateAverage()); // Outputs: 87.5
Advantages of Objects
- Data Grouping: Group related data and functionality.
- Code Reusability: Use methods for repetitive tasks.
- Clear Structure: Makes code organized and readable.