Hey there, friend!
Welcome to our tutorial on Objects in JavaScript! You've already learned about variables, data types, and conditional statements, so it's time to take your skills to the next level.
In this tutorial, we'll create a 'person' object with properties like 'name', 'age', and 'gender'. By the end of this tutorial, you'll understand how to work with objects and be ready to learn about For Loops in our next tutorial.
Step 1: Create a new object
Open your index.js
file and let's get started!
To create a new object, we use the {}
syntax. Think of an object like a container that holds key-value pairs, where each key is a property and each value is the property's value.
Add the following code to your index.js
file:
let person = {}
Run the code by clicking the "Run" button. You won't see any output in the console yet, but that's okay!
Step 2: Add properties to the object
Let's add some properties to our person
object. We'll add 'name', 'age', and 'gender' properties.
Update your code with the following:
let person = { name: "John Doe", age: 30, gender: "Male",}
Run the code again. You still won't see any output in the console, but we're getting closer!
Step 3: Accessing object properties
Now that we have our person
object with properties, let's access them using dot notation.
Add the following code to access each property:
console.log(`Name: ${person.name}`);console.log(`Age: ${person.age}`);console.log(`Gender: ${person.gender}`);
Run the code one more time. This time, you should see the following output in the console:
Name: John DoeAge: 30Gender: Male
Woohoo! You've just created and accessed an object's properties!
Real-world example: Think of a social media profile. Each profile has properties like name, age, and gender. We can represent this data using an object, making it easy to access and manipulate the information.
Step 4: Update object properties
Let's update our person
object's 'age' property.
Add the following code:
person.age = 31;console.log(`Updated Age: ${person.age}`);
Run the code again. You should see the updated age in the console:
Updated Age: 31
You've successfully updated an object's property!
That's it for this tutorial! You now know how to create an object, add properties, access them, and update them.
In our next tutorial, we'll explore For Loops, which will help you iterate over arrays and objects even more efficiently.
Keep practicing, and you'll become a JavaScript master in no time!
Happy coding, and see you in the next tutorial!
Tests