Welcome to our deep dive into JavaScript Object Methods! In this comprehensive guide, we'll explore various methods that allow you to manipulate and interact with objects in a practical, beginner-friendly way. Let's get started!
Before we dive into the methods, let's clarify what we mean by Object Methods. An Object Method is a function that belongs to an object. It allows you to perform specific actions on the object itself.
First, let's create a simple object:
let car = {
brand: "Tesla",
model: "Model 3",
year: 2020
};In this example, car is an object with three properties: brand, model, and year.
Now that we've created an object, let's look at some common object methods:
Object.keys(obj) 📝This method returns an array of an object's property names.
let carProperties = Object.keys(car);
console.log(carProperties); // ["brand", "model", "year"]Object.values(obj) 📝This method returns an array of an object's property values.
let carValues = Object.values(car);
console.log(carValues); // ["Tesla", "Model 3", 2020]obj.property 📝You can access an object's property directly using the dot notation.
console.log(car.brand); // "Tesla"obj['property'] 📝You can also access an object's property using bracket notation, which is useful when the property name is stored in a variable.
let propertyName = "brand";
console.log(car[propertyName]); // "Tesla"obj.method(params) 📝You can call an object's method using dot notation, passing any necessary parameters.
// Let's assume car has a method called "drive"
car.drive(); // Calls the drive method on the car objectWhat does `Object.keys(obj)` return?
Stay tuned for Part 2, where we'll dive deeper into more object methods and practical examples! 🚀