Objects in JavaScript
Introduction Link to heading
An object in JavaScript is a collection of data and functions that are grouped together under a single name. Objects are a fundamental tool for organizing and structuring JavaScript code.
Object creation Link to heading
- You can create an object using object literal notation, which consists of two curly braces
{}
and a comma-separated list of properties and values.
Example: Link to heading
const myCar = {
make: "Toyota",
model: "Corolla",
year: 2020,
};
Access to properties: Link to heading
- You can access a property of an object using dot notation. or the square bracket notation [].
Example: Link to heading
console.log(myCar.make); // Prints "Toyota"
console.log(myCar["model"]); // Prints "Corolla"
Object methods: Link to heading
- Objects can have methods, which are functions that are defined within the object.
- Methods can be used to perform actions on the object.
Example Link to heading
myCar = {
make: "Toyota",
model: "Corolla",
year: 2020,
carDetails: function () {
console.log(`Car ${this.model} ${this.year}`);
},
};
myCar.carDetails(); // Prints "Car Corolla 2020"
Note: The this
keyword within a method refers to the current object.
More about objects Link to heading
- You can add new properties and methods to an object after its creation.
- You can remove properties and methods from an object.
- You can use objects to create complex data structures such as lists, trees, and sets.
Keep learning about objects to write more organized and flexible JavaScript code!