Welcome to the JavaScript (JS) Object Definitions tutorial! In this lesson, we'll learn how to create, manipulate, and understand JavaScript objects. We'll start from the basics and gradually move towards more complex examples.
An object in JavaScript is a collection of related data and functions (methods) that operate on that data. It's a way to organize data in a more structured and manageable manner.
Objects in JavaScript are similar to real-world objects. For example, a car is an object with properties like color, model, and speed, and methods like accelerate and brake.
You can create an object in JavaScript using three methods:
Let's start with the most common method - Object Literal.
let car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
color: "Blue",
// Methods
accelerate: function() {
this.speed += 10;
console.log(`Car is now going ${this.speed} km/h.`);
},
brake: function() {
this.speed -= 5;
console.log(`Car is now going ${this.speed} km/h.`);
}
};š Note: In the above example, this refers to the current object.
Now, let's see how to create the same object using a Constructor Function:
function Car(brand, model, year, color) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
this.accelerate = function() {
this.speed += 10;
console.log(`Car is now going ${this.speed} km/h.`);
};
this.brake = function() {
this.speed -= 5;
console.log(`Car is now going ${this.speed} km/h.`);
};
}
let myCar = new Car("Toyota", "Corolla", 2020, "Blue");š Note: Using a constructor function, you can create multiple objects of the same type (Car in this case).
You can access an object's properties using dot notation (object.property) or bracket notation (object['property']). To modify an object's property, simply assign a new value to it.
console.log(myCar.brand); // Output: "Toyota"
myCar.color = "Red";
console.log(myCar.color); // Output: "Red"You can call an object's method by invoking it like a function.
myCar.accelerate(); // Output: "Car is now going 10 km/h."
myCar.brake(); // Output: "Car is now going 5 km/h."How can you create a JavaScript object using the Object Literal method?
In this tutorial, we've learned about JavaScript objects, how to create them using Object Literals and Constructor Functions, and how to access, modify, and call their properties and methods.
Stay tuned for more lessons on JavaScript where we'll dive deeper into the world of objects and other exciting topics!
Happy coding! š”š”š”