Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Working with JavaScript Objects

Hello! Welcome to your next lesson on JavaScript fundamentals.

In our last session, we covered how to create and use functions to write reusable blocks of code. This is a powerful way to organize actions and logic in your application.

Today, we'll shift our focus from organizing actions to organizing data. This lesson addresses the learning outcome: Model data structures such as user profiles or component states using JavaScript objects by creating, accessing, and modifying their properties.

As a product designer, you constantly work with structured information—a user's profile, the properties of a UI component, or the details of a product. JavaScript objects are the primary tool we use to represent these real-world things in code. They allow us to group related pieces of information into a single, tidy package.

1. Why Do We Need Objects?

Imagine you're building a user profile page. You might need to store a user's first name, last name, age, and login status. Without objects, you'd create separate variables for each piece of data:

let firstName = "Jane";
let lastName = "Doe";
let age = 32;
let isLoggedIn = true;

This works for one user, but what happens when you have two, or a hundred? The number of variables would explode, making the code difficult to manage. Objects solve this by letting us group related data together.

This short video uses a great visual metaphor to explain why this grouping is so useful.

JavaScript objects explained the visual way

Let's start with a visual explanation of why objects are so helpful for organizing data. This video from 3dCodeWorld uses a bookshelf analogy to make the concept clear.

Watch from the beginning to 04:23. Focus on: How objects help reduce the clutter of having too many separate variables. The analogy of kitchen drawers or bookshelves for keeping related things together. The core terminology: object, property, key, and value.

To recap the video's terminology:

  • Object: The entire collection, like a cabinet or a user profile.
  • Property: A single piece of information within the object, like one signed file.
  • Key: The name of a property (e.g., "name").
  • Value: The data associated with a key (e.g., "John").

A property is the key-value pair together.

2. Creating, Accessing, and Modifying Objects

Now that we understand the "why," let's dive into the "how." The most common way to create an object in JavaScript is with the object literal syntax, which uses curly braces {}.

Objects

This article from javascript.info provides a clear, concise guide to the basic syntax of objects. It has helpful diagrams that are great for visual learners.

Please read the start of the article, from the beginning down to the section titled "Square brackets". This will cover: The basic syntax for creating an object with properties. How to access, add, and delete properties using dot notation.

Creating an Object

As you just read, you can create an object and assign it to a variable like this:

// This object models a user profile
const userProfile = {
  firstName: "Jane",
  lastName: "Doe",
  age: 32,
  isLoggedIn: true
};

This single userProfile variable now holds all the related information, neatly organized.

Accessing and Modifying Properties

You can read a value from an object using dot notation:

console.log(userProfile.firstName); // Outputs: "Jane"

You can also use dot notation to change a value or add a new property:

// Modifying an existing property
userProfile.age = 33; 
console.log(userProfile.age); // Outputs: 33

// Adding a new property
userProfile.role = "Admin";
console.log(userProfile.role); // Outputs: "Admin"

3. Dot Notation vs. Bracket Notation

Dot notation is simple and easy to read, but it has limitations. It doesn't work for property keys that have spaces or special characters, or when the key is stored in a variable. For those cases, we use bracket notation.

Objects

Let's continue with the same javascript.info article to understand the powerful alternative to dot notation.

Read the section titled "Square brackets". Pay close attention to the two main use cases: Accessing properties with multi-word names. Accessing properties using a variable.

Here’s a summary of when to use each:

  1. Dot Notation (object.key):

    • Use this most of the time.
    • The key must be a valid JavaScript identifier (no spaces, doesn't start with a number).
    • Example: userProfile.firstName
  2. Bracket Notation (object['key']):

    • Use this when the key is a string with spaces or special characters.
    • Example: userProfile['preferred theme'] = 'dark';
    • Use this when the key name is stored in a variable (dynamic access).
    • Example:
      let keyToAccess = 'lastName';
      console.log(userProfile[keyToAccess]); // Outputs: "Doe"
      

This ability to access properties dynamically is incredibly powerful in front-end development, as you often don't know which piece of data a user will request until they click a button or fill out a form.

4. Your Turn: Modeling a Component's State

Let's put this into practice with an exercise that mirrors a real-world design task. Imagine you're designing a "subscribe" button component. This component has several states you need to manage:

  • The text it displays (e.g., "Subscribe", "Subscribed!").
  • Its color.
  • Whether it's currently disabled.

We can model all of this with a single JavaScript object.

Your Task:

  1. Open your code editor and create a new HTML file.

  2. Add the following basic structure:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Object Practice</title>
    </head>
    <body>
      <h1>Component State</h1>
      <script>
        // Your JavaScript code will go here
      </script>
    </body>
    </html>
    
  3. Inside the <script> tag, perform the following steps. Use console.log() to check your work at each stage.

    a. Create the object: Define an object named subscribeButtonState. It should have three properties:
    * buttonText with the string value "Subscribe".
    * isDisabled with the boolean value false.
    * "background color" with the string value "blue". (Note the space in the key!)

    b. Access properties:
    * Log the buttonText to the console using dot notation.
    * Log the "background color" to the console. You'll need to use bracket notation for this.

    c. Modify properties: Imagine a user has just clicked the button. Update the object to reflect the new state:
    * Change the buttonText to "Subscribed!".
    * Change isDisabled to true.
    * Change the "background color" to "grey".

    d. Log the final state: After making the changes, log the entire subscribeButtonState object to the console to see the final result.

Click here to see the solution
// a. Create the object
const subscribeButtonState = {
  buttonText: "Subscribe",
  isDisabled: false,
  "background color": "blue"
};
console.log("Initial State:", subscribeButtonState);

// b. Access properties
console.log("Initial text:", subscribeButtonState.buttonText);
console.log("Initial color:", subscribeButtonState["background color"]);

// c. Modify properties
subscribeButtonState.buttonText = "Subscribed!";
subscribeButtonState.isDisabled = true;
subscribeButtonState["background color"] = "grey";

// d. Log the final state
console.log("Final State:", subscribeButtonState);

This exercise shows how an object can act as a single source of truth for the state of a UI component, making it easy to manage and update.

Conclusion

Great job! You've learned how to use JavaScript's most fundamental data structure. Objects are essential for building any non-trivial application, and you'll be using them in every lesson from here on out.

Key Takeaways:

  • Objects are collections of key-value pairs used to group related data.
  • The most common way to create an object is the object literal syntax: const myObj = { key: 'value' };.
  • You can access and modify properties using dot notation (myObj.key) for simple keys.
  • For keys with spaces or for dynamic access using variables, you must use bracket notation (myObj['key']).
  • Objects are perfect for modeling real-world entities like user profiles or the state of a UI component.

In our next lesson, we will look at another crucial data structure: arrays. While objects are ideal for storing unordered data with named keys, arrays are used for storing ordered lists of items, like a list of blog posts, user comments, or items in a shopping cart.

Can't find a good explanation? Sign up and we'll make it for you

Sign up