JavaScript Fundamentals 04: Data Structures Arrays, and set()

Sets and arrays are both fundamental data structures in JavaScript, but they serve different purposes and have distinct characteristics.

JavaScript Fundamentals 04: Data Structures Arrays, and set()

Today, we're diving into one of the core data structures in JavaScript: Arrays. Plus, we'll explore the utility of the set() method for unique collections.

Sets and arrays are both fundamental data structures in JavaScript, but they serve different purposes and have distinct characteristics.

Watch the Video

Arrays are ordered collections of elements that can contain duplicates and offer a wide array of methods to manipulate the data they hold, including adding, removing, and accessing elements based on their index. Arrays are ideal for scenarios where order matters and when you need to store multiple instances of the same value.

Sets, introduced in ES6 (ECMAScript 2015), represent a collection of unique values. Unlike arrays, sets do not allow duplicate entries, ensuring each element is distinct. Sets do not have indexed access to elements, meaning you cannot directly retrieve a value by its position. Instead, sets are optimized for checking the presence of values, adding new values, and removing values. Sets are particularly useful when you need to maintain a collection of unique items, such as a list of unique user IDs or tags.

Understanding Arrays

Arrays in JavaScript are used to store multiple values in a single variable. They are incredibly versatile for handling lists of elements, such as collections of names, numbers, or even other arrays.

Creating an Array:

let fruits = ['Apple', 'Banana', 'Cherry'];

In this example, fruits is an array that holds three strings. Each item in an array has an index, starting with 0 for the first element. Therefore, 'Apple' is at index 0, 'Banana' is at index 1, and so on.

You may also see arrays created as formal objects like this:

let sports = new Array('baseball', 'football', 'basketball', 'hockey');

Regardless of the method used to create the array, the result is the same– a list of items referenced by the array name.

You can create an empty array that you will populate later like this:

let family = [];

Manipulating Arrays

Arrays come with a variety of methods for manipulation, including adding, removing, and finding items within the array.

  • Adding Items: Use push() to add items to the end of an array.
  • Removing Items: Use pop() to remove the last item from an array.
fruits.push('Dragonfruit'); // Adds 'Dragonfruit' to the end
fruits.pop(); // Removes 'Dragonfruit'

Looping Through Arrays with a For Loop

One of the most common tasks when working with arrays is iterating over each element to perform operations, such as displaying each item on the screen, calculating sums, or applying transformations. A for loop is a versatile tool for traversing all elements in an array.

The Basic For Loop Structure for Arrays

When using a for loop to iterate through an array, you typically start your counter at 0 (since array indices in JavaScript are zero-based), continue the loop as long as the counter is less than the array's length, and increment the counter after each iteration.

Example: Displaying Array Elements

Let's say we have an array of fruits and we want to log each fruit to the console:

let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

for (let i = 0; i < fruits.length; i++) {

In this example, fruits.length gives us the total number of items in the array. The loop runs from i = 0 to i = fruits.length - 1, ensuring each element is accessed and printed out.

Real-World Application: Summing Numbers in an Array

Consider an array containing numerical values. You want to calculate the sum of all numbers in the array. Here's how you can use a for loop to accomplish this task:

let numbers = [10, 20, 30, 40, 50];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];

console.log('Total Sum:', sum);

In this scenario, the loop iterates over each element in the numbers array, adding the current element's value to the sum variable. After the loop completes, sum contains the total of all numbers in the array.

Why Looping Through Arrays Is Useful

Looping through arrays is a cornerstone of working with collections of data. Whether you're rendering items on a web page, processing user input, or analyzing data sets, loops offer a straightforward way to access and manipulate each element within an array. Mastering array loops enables you to:

  • Dynamically generate content or UI elements based on array data.
  • Perform bulk operations on data, such as filtering, sorting, or transforming elements.
  • Aggregate or summarize data, useful in applications like reporting tools or statistical analyses.

Expanding Your Knowledge

As you become more comfortable with for loops and arrays, experiment with other loop constructs like for...of loops, which offer a more concise syntax for iterating over iterable objects like arrays. Additionally, array methods such as forEach(), map(), and filter() provide high-level abstractions for common looping operations, often leading to cleaner and more expressive code.

Creating Unique Collections with set()

While not a method of Array, JavaScript's Set object lets you store unique values of any type, whether primitive values or object references.


let mySet = new Set([1, 2, 3, 3, 4]);
console.log(mySet); // Set(4) {1, 2, 3, 4}

This Set object contains only unique numbers, even though the number 3 was added twice.

Try it Yourself!

Exercise 1: Working with Arrays
Create an array of your favorite movies. Add two more using push(), then remove the last one.

Exercise 2: Understanding Sets
Create a Set containing a list of colors. Try adding a duplicate color to see how Set ensures uniqueness.

Exercise 3: Looping Through and Array
Create an array of numbers representing daily temperatures. Use a for loop to calculate the average temperature and log it to the console. Then, think about how you might use a loop to identify days with temperatures above a certain threshold.

By integrating these looping techniques into your JavaScript practice, you'll unlock powerful ways to work with and manipulate data in your applications.

Final Thought

Arrays and their manipulation are fundamental in JavaScript programming, offering structured ways to store and interact with data. The Set object further extend these capabilities, providing efficient ways to process and manage data. As you become more comfortable with these concepts, you'll find them invaluable for developing dynamic and data-driven web applications.