Learn JavaScript Β· 5/15

Essential Data Structures: Arrays and Objects

6 min read

Essential Data Structures: Arrays and Objects πŸ€–

Welcome! Data structures are the foundation of programming, allowing us to organize and manage data effectively. Today, we'll dive into two of the most fundamental data structures in JavaScript: Arrays and Objects. Think of them as your primary tools for building anything from a simple to-do list to a complex social media application.


1. Arrays: Managing Ordered Lists of Data πŸ“Š

Definition: An array is an ordered collection of values. Each value is called an element, and each element has a numeric position, known as its index.

The Problem: Imagine you're building a music playlist application. You need to store a list of song titles. Without arrays, you might end up creating a separate variable for each song:

javascript
let song1 = "Bohemian Rhapsody";
let song2 = "Stairway to Heaven";
let song3 = "Hotel California";
// This is getting tedious...

This approach is clumsy, hard to manage, and doesn't scale. What if you wanted to add a fourth song, or the tenth, or the hundredth? 😱 That's where arrays come to the rescue!

The Solution: Arrays

Arrays allow you to group related data into a single, ordered list.

Creating an Array

The most common way to create an array is using array literal syntax: [].

javascript
// An array of strings
let songPlaylist = ["Bohemian Rhapsody", "Stairway to Heaven", "Hotel California"];

// An array of numbers
let luckyNumbers = [7, 42, 108];

// An array with mixed data types (though it's good practice to keep them consistent)
let mixedBag = ["Hello", 42, true];

Accessing Array Elements

You can access individual elements in an array using their index. In JavaScript, array indices start at 0. So, the first element is at index 0, the second at index 1, and so on.

javascript
let songPlaylist = ["Bohemian Rhapsody", "Stairway to Heaven", "Hotel California"];

console.log(songPlaylist[0]); // Output: "Bohemian Rhapsody"
console.log(songPlaylist[1]); // Output: "Stairway to Heaven"

// What happens if you try to access an index that doesn't exist?
console.log(songPlaylist[5]); // Output: undefined

🧠 Fun Fact: The choice of 0-based indexing in many programming languages is a topic of much debate. It simplifies certain computer arithmetic, but it can be a common source of bugs for beginners (and even experienced developers!).

Under the Hood: When you create an array, JavaScript allocates a contiguous block of memory to store its elements. This makes accessing elements by their index very fast, as the computer can calculate the exact memory location of an element based on its index.


2. Basic Array Methods: push, pop, shift, and unshift πŸ”„

Your data is rarely static. You'll often need to add or remove items from your lists. Let's look at some essential array methods for these tasks.

Scenario: You're managing a queue for a popular new food truck. 🚚 People are constantly joining and leaving the line.

push(): Adding to the End

The push() method adds one or more elements to the end of an array.

javascript
let customerQueue = ["Alice", "Bob"];
console.log(customerQueue); // Output: ["Alice", "Bob"]

customerQueue.push("Charlie");
console.log(customerQueue); // Output: ["Alice", "Bob", "Charlie"]

Now Charlie is at the back of the line.

pop(): Removing from the End

The pop() method removes the last element from an array and returns that element.

javascript
let customerQueue = ["Alice", "Bob", "Charlie"];
console.log(customerQueue); // Output: ["Alice", "Bob", "Charlie"]

let servedCustomer = customerQueue.pop();
console.log(servedCustomer); // Output: "Charlie"
console.log(customerQueue); // Output: ["Alice", "Bob"]

Charlie just got their food and is happily on their way.

unshift(): Adding to the Beginning

The unshift() method adds one or more elements to the beginning of an array.

javascript
let customerQueue = ["Alice", "Bob"];
console.log(customerQueue); // Output: ["Alice", "Bob"]

customerQueue.unshift("VIP Dave");
console.log(customerQueue); // Output: ["VIP Dave", "Alice", "Bob"]

VIP Dave just cut the line! 😜

shift(): Removing from the Beginning

The shift() method removes the first element from an array and returns that element.

javascript
let customerQueue = ["VIP Dave", "Alice", "Bob"];
console.log(customerQueue); // Output: ["VIP Dave", "Alice", "Bob"]

let nextInLine = customerQueue.shift();
console.log(nextInLine); // Output: "VIP Dave"
console.log(customerQueue); // Output: ["Alice", "Bob"]

It's finally VIP Dave's turn to order.

Industry Practice: While unshift() and shift() are useful, be aware that they can be slower than push() and pop() on very large arrays. This is because adding or removing elements from the beginning requires re-indexing all the other elements in the array.


3. Objects: Structuring Data with Key-Value Pairs πŸ”‘

Definition: An object is a collection of key-value pairs. The keys are strings (or Symbols), and the values can be any data type, including other objects or arrays.

The Problem: Let's say you want to store information about a user. You could use separate variables:

javascript
let userName = "dev_person";
let userFollowers = 1337;
let isUserVerified = true;

This works, but the data is scattered. There's no clear connection that all these variables describe the same user. Objects solve this by grouping related data.

The Solution: Objects

Objects allow you to structure data in a more meaningful way.

Creating an Object

The most common way to create an object is using object literal syntax: {}.

javascript
let userProfile = {
  username: "dev_person",
  followers: 1337,
  isVerified: true,
  favoriteFoods: ["pizza", "sushi", "tacos"]
};

Here, username, followers, isVerified, and favoriteFoods are the keys, and "dev_person", 1337, true, and the array ["pizza", "sushi", "tacos"] are their corresponding values.


4. Accessing and Modifying Object Properties ✍️

Once you have an object, you'll need to be able to read and update its properties.

Dot Notation

Dot notation is the most common way to access an object's properties. It's clean and easy to read.

javascript
let userProfile = {
  username: "dev_person",
  followers: 1337
};

// Accessing properties
console.log(userProfile.username); // Output: "dev_person"

// Modifying properties
userProfile.followers = 1500;
console.log(userProfile.followers); // Output: 1500

Bracket Notation

Bracket notation is also used to access properties. It's required when the property key is stored in a variable or when the key has spaces or special characters.

javascript
let userProfile = {
  "user name": "dev_person",
  followers: 1337
};

// Accessing with a key that has a space
console.log(userProfile["user name"]); // Output: "dev_person"

// Accessing with a variable
let propertyToAccess = "followers";
console.log(userProfile[propertyToAccess]); // Output: 1337

Adding New Properties

You can add new key-value pairs to an existing object at any time.

javascript
let userProfile = {
  username: "dev_person"
};

// Adding a new property
userProfile.location = "The Internet";

console.log(userProfile); // Output: { username: "dev_person", location: "The Internet" }

Hands-On Practice: In web development, you'll constantly work with objects. For example, when you get data from an API (like user data from a server), it's almost always in the form of JSON (JavaScript Object Notation), which you'll then parse into JavaScript objects to use in your application.


Further Reading πŸ“š

For a deeper dive into these topics, check out the official documentation and other helpful resources:

Challenge

You are tasked with managing the data for a social media profile. Below is a userProfile object. Perform the following sequential operations on it:

  1. A new, high-priority post must be added to the very beginning of the posts array. The new post object is: { postId: 104, content: "Learning JavaScript is fun!", comments: [] }.
  2. Add a new property to the main userProfile object to store the user's location. The key must be "user location" (note the space) and the value should be "Cyberspace". You must use the correct notation to handle a key with a space.
  3. A new comment, "Totally agree!", needs to be added to the comments array of the post with postId equal to 102.
  4. The user's follower count has increased. Update the followers property by adding 50 to its current value.
  5. The oldest post needs to be archived. Remove the very last post from the posts array.

Expected result

After your code executes, the userProfile object should be modified to reflect all the changes. The final object should have:

  • A followers count of 1300.
  • A new property "user location" with the value "Cyberspace".
  • The posts array should contain exactly three posts.
  • The first post in the posts array should be the new one with postId: 104.
  • The post with postId: 102 should have one comment in its comments array: "Totally agree!".
  • The original post with postId: 103 should no longer be present in the posts array.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.