Logo
Unit 8 – JavaScript Objects

JavaScript Objects

Duration: 5 minutes

Hello there, JavaScript fans!

After understanding arrays, it’s time to move on to another crucial idea: objects. Similar to improved arrays, objects allow you to store and access data using named properties rather than an index.

Understanding Objects

In JavaScript, objects allow us to create a single entity that holds multiple related values. Instead of using an index, we use named properties or keys to store and access data.

A basic object can be declared as follows:

let car = {
brand: "Toyota",
model: "Camry",
year: 2020
};

Here, brand, model, and year are properties of the object car.

Accessing and Modifying Object Data

To access data from an object, you can use either dot notation or bracket notation:

console.log(car.brand); // Outputs: Toyota

To modify a property’s value:

car.year = 2022;
console.log(car.year); // Outputs: 2022

Methods in Objects

Methods are essentially functions that are properties of an object. Here’s how you can add a method to our car object:

car.displayInfo = function() {
console.log(`This is a ${this.brand} ${this.model} from ${this.year}.`);
};

Exercise

Your task is to dive deeper into objects:

  • Object Creation: Create an object named person with properties firstName, lastName, and age.
  • Accessing Data: Print out the person’s first name.
  • Modifying Data: Change the age property to a new value.
  • Adding a Method: Add a method called fullName that returns the person’s full name when called.
  • Using the Method: Call the fullName method to print out the person’s full name.
  • Challenge: Add another property of your choice and utilize it in a new method.

By the end of this exercise, you should have a solid understanding of the basic operations related to JavaScript objects.

Conclusion

Congratulations! You have now gained access to objects, a fundamental building block of JavaScript and many other programming languages. Objects give your code organization and clarity, enabling you to accurately mimic real-world situations.

As your knowledge of JavaScript grows, you’ll discover that objects are a strong ally, particularly when working with increasingly complicated applications. There is always more to learn and grasp, so keep trying and developing your understanding.

Next Tutorial: Basic DOM Manipulation

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!