In this tutorial, we aim to provide a comprehensive guide to understanding JavaScript objects. We will learn how to create, access, and manipulate objects in JavaScript.
By the end of this tutorial, you should be able to:
- Understand what JavaScript objects are
- Create your own objects
- Access and modify properties of an object
- Use methods with objects
Prerequisites: Basic understanding of JavaScript syntax and data types.
JavaScript objects are containers for named values, called properties and methods. The properties of an object define the characteristics of the object, and the methods define the actions the object can perform.
You can define (and create) a JavaScript object with an object literal:
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
In the example above, 'person' is an object. The object has four properties: firstName, lastName, age and eyeColor.
You can access object properties in two ways:
console.log(person.firstName); // Output: "John"
console.log(person["lastName"]); // Output: "Doe"
You can change the value of an object property using the assignment operator:
person.firstName = "Jane"; // changes the firstName property to "Jane"
Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.
let person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, fullName is a method, and it will return "John Doe" when called: person.fullName()
.
let car = {
make: "Toyota",
model: "Corolla",
year: 2020,
color: "red"
};
console.log(car); // Output: { make: 'Toyota', model: 'Corolla', year: 2020, color: 'red' }
console.log(car.make); // Output: "Toyota"
console.log(car["model"]); // Output: "Corolla"
car.year = 2021; // changes the year property to 2021
console.log(car.year); // Output: 2021
let person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Output: "John Doe"
In this tutorial, we've learned what JavaScript objects are, how to create them, and how to access and modify their properties. We've also learned how to use methods with objects.
The next step in your learning journey could be learning about JavaScript Object Prototypes, or perhaps exploring more about functions and how they work with objects.
Additional resources:
1. Mozilla Developer Network - JavaScript objects
2. W3Schools - JavaScript Objects
Solutions with explanations and tips for further practice can be found in the additional resources provided.