14. JavaScript: Objects

14. JavaScript: Objects

🎯 Learning Goals

  • Create an object and access data from them
  • Understand why we sometimes choose to use objects over arrays (and vice versa)
 

📗 Technical Vocabulary

  • Collection
  • Dot Notation
  • Key/Value pair
  • Object
 
💻
Fork and use this template throughout the lesson → Lesson 14: JavaScript: Objects
🌤️
Warm-Up
Pretend you are going to create an app that has a feature that reminds you of friends’ birthdays. Somewhere in the program, you need to store names and birthdays.
With your breakout group, brainstorm at least one way that you could store a list of both names and birthdays.
Be ready to share out:
  • What you came up with
  • The benefits of this solution
  • The drawbacks of this solution

🌎 Objects

An Object is another complex data type available in JavaScript. Objects, like Arrays, can be classified as collections. There is, however, one big difference between them and arrays: Objects are not ordered by index (0, 1, 2, etc.). Instead, each piece of data has a ‘label’ instead of a number. We call the labels keys and the data valueskey/value pairs is a term you will hear a lot.

When to use Objects

We just got the hang of arrays and are feeling pretty great about them - when/why do we also need objects?
  • When we don’t care about the order of items (array)
  • When we need an associative relationship (title for some info)
If I wanted to make a list of the handles of all my favorite creators on TikTok, I should use an array. They are all strings, and they are all holding the same type of information. I don’t care about the number of followers they have, if they are verified, or anything else.
If I wanted to make a list of the handles of all my favorite creators on TikTok and their number of followers, I should use an object. There is an associative relationship between each creator and their follower count.
💭
Think About It: Array or Object?
For each set of data, would an array or object be better to store it? Why? Be ready to share out.
  • List of all of the students in class
  • List of states and their capitals
  • List of things to pack for vacation
  • Names of all the Instagram accounts I follow
  • List of scholar names and the school they attend
  • Ingredients and amount of each ingredient to bake a cake
  • All my favorite restaurants
🤖 AI Connection
Ask an AI tool for guidelines about when to use an array versus object when coding in JavaScript. Was the explanation helpful?

Syntax

Think back to the playlist example from our work with Arrays. In addition to the name of the songs themselves, playlists also often display the name of the singer(s).
We can store the list of songs in a JavaScript object if we want to make sure that each song is associated with the artist behind it. The key will be the song name, and the value will be the singer’s name. We can then create a variable called viralSingers to store the data.
const viralSingers = { runTheWorldGirls: "Beyonce", prettyGirlRock: "Keri Hilson", flowers: "Miley Cyrus", truthHurts: "Lizzo", noScrubs: "TLC", }
💼
Syntax Takeaways
  • All keys should be written in camelCase and should not be enclosed in quotes.
  • To indicate that the key name has ended and the value will be provided next, we use a colon :
  • A value can be a string, number, boolean, array, or another object. For the most part, we will use strings and numbers. All values in one object do not have to be the same data type.
  • A comma separates each key/value pair.
notion image

Access a Value

To access a value in a specific object, we have to first tell the program which object to look at. Then we use a period ., then call the key, or label, associated with the value we want to access.
console.log(viralSingers.flowers); //=> Miley Cyrus console.log(viralSingers.prettyGirlRock); //=> Keri Hilton
The syntax used above to access a value is called dot notation.

Update, Add or Remove Data

We won’t go into detail on how to do this here, as it likely won’t be used during camp. If you are curious to learn more or find yourself needing a resource while working on your personal project, here are a couple of resources you might want to check out:
 
✏️
Try-It | Objects
Create a family object with keys that are family or friend titles (i.e. “sibling”, “bestFriend”) and values that are the name of that family member or friend. Pets are family, too!
  • Aim to have at least 6 family members of friends in your family object
  • Print to the console the entire object
  • Print to the console 3 individual names
Click here for a Medium Challenge 🌶🌶
What happens if you have three siblings or a whole group of best friends? Creating keys like sibling1 and sibling2 makes your code messy and hard to work with. Update your object so that at least one of your keys stores an array of strings instead of just a single string. This allows one title or key to hold multiple names. You can add new information to an object after you’ve created it using dot notation to create a new key and assign its value (e.g., family.bestFriends = ["Mira", "Zoey"]).

Objects IRL

Like arrays, objects are everywhere in the apps you use every day. Take this Apple Music playlist:
notion image
A playlist like this doesn't just store song names. It also holds multiple pieces of information about each song. In code, that same playlist in JavaScript code might look something like this:
const viralHits = [ { title: "Run the World (Girls)", artist: "Beyonce", albumName: "4", durationInSeconds: 238 }, { title: "Pretty Girl Rock", artist: "Keri Hilson", albumName: "No Boys Allowed (Deluxe)", durationInSeconds: 243 }, { title: "Flowers", artist: "Miley Cyrus", albumName: "Endless Summer Vacation", durationInSeconds: 200 }, { title: "Truth Hurts", artist: "Lizzo", albumName: "Cuz I Love You", durationInSeconds: 173 }, { title: "No Scrubs", artist: "TLC", albumName: "Fanmail", durationInSeconds: 214 } ];
This is still an array with 5 elements, but now each element is an object, with its own bundle of related data. You won't always need a structure this complex, but this is a good example of how arrays and objects work together to model real-world data!

Putting It All Together

Objects have a little more going on than strings or numbers, but you now have the information you need about them!
📝
Practice | Creating and Accessing Objects
  1. Declare a variable called myInfo that stores an object. Include keys for your name, birthday, and two fun facts. Use console.log(myInfo) to check your syntax, then use dot notation to log only your birthday.
  1. Objects are perfect for filling out “templates” like user profiles. Let's use your myInfo object to fill out a digital user profile. Instead of typing your info directly into the HTML file, use your myInfo object and textContent to populate the digital profile on the page!
Click Here for a Medium Challenge 🌶️🌶️
Add a new key to your object called favoriteColor(e.g.,"purple"). Use the DOM to change the style.color of your heading to match that value!
Click Here for a Spicy Challenge 🌶️🌶️🌶️
Real apps often have many users! Create a variable called friends that stores an array of objects. Each object should represent a different person with their own name, birthday, and hobby.
  • Create at least 3 friend objects inside your array.
  • Use a forEach loop to go through the array.
  • Inside the loop, use innerHTML to create a new profile card for each person and add it to the page!
Click here for a hint!
You can use innerHTML += to keep adding HTML to a container. With string interpolation (backticks!) you can write an HTML snippet and drop in values from each object using ${}!
const pets = [ { name: "Mochi", type: "cat" }, { name: "Biscuit", type: "dog" } ]; const container = document.querySelector("#pet-container"); pets.forEach(function(pet) { container.innerHTML += ` <div class="card"> <h2>${pet.name}</h2> <p>Type: ${pet.type}</p> </div> `; });
🤖 AI Connection
Have you encountered an error message that prevents your code from running? Consider asking an AI tool where in your file to look for an error. You might just need a hint to support your own debugging!

AI-Assisted Coding in CodeSandbox

AI-assisted coding means using AI tools to assist with writing, debugging, and improving code. Similar to large language models like ChatGPT, CodeSandbox’s predictive code completion model, Codeium, uses machine learning to make predictions and suggest relevant completions. If you’d like to test out using Codeium as you work on your Capstone Project, you’re welcome to follow the steps below!
Step 1: Convert your Sandbox to a Devbox
Your Sandbox needs to be a Devbox. Convert it into a Devbox by clicking the button next to Fork and select Fork as Devbox. Click Convert. This may take a few minutes.
notion image
Step 2: Update the AI Permissions in your Workspace
Go to your workspace settings. Choose a workspace. Click Permissions and make sure your AI permissions are enabled.
notion image
Step 3: Toggle on the Code completion by Codeium setting in your Devbox
Open your Devbox from earlier. Click the square in the upper left-hand corner. Select Settings. Toggle Code completion by Codeium to be on.
notion image
There are a few things to consider related to using the predictive code completion tool:
  • The suggestions aren’t always accurate. As we know, machine learning models are really fancy prediction machines based on past data and they won’t always correctly predict what you’re trying to do. Be sure to review any suggested code carefully before accepting it.
  • It can be distracting. Some developers find predictive completion helpful, while others find it intrusive. Pay attention to how it affects your workflow over the next few lessons and decide if it’s beneficial for you.
  • Suggestions may not follow best practices. While the suggestions can speed up coding, they might not always align with best practices or the most efficient solutions. Always double-check for readability, efficiency, and adherence to coding standards.
Ultimately, predictive code completion in CodeSandbox is a tool that can enhance your workflow, but its usefulness depends on the complexity of your project and your personal coding style! As you work through the capstone project, take note of how it impacts your efficiency and decide whether it’s a feature you want to keep enabled.
page icon
For a summary of this lesson, check out the 14. JavaScript: Objects One-Pager!