Skip to Content

Arrays and Loops

Strings and numbers may be our building blocks, but as your scripts get more complex, you are going to need a way to deal with large quantities of them. Luckily, JavaScript has a couple of data types that are used for just that.

Arrays

An Array is an ordered collection of items (Strings, numbers, or other things).

Arrays are a way to store multiple values in a single variable. They are a special type of object that has a length property and a series of numbered properties. Each numbered property is called an element, and each element can store a value of any type.

An Example of an array is:

const fruits = ['apple', 'banana', 'orange'];

Accessing Elements of an Array

To access the elements of an array, you can use the index number. The index number starts from 0, so the first element of an array is at index 0, the second element is at index 1, and so on.

For example, to access the first element of the fruits array, you can use the following code:

const fruits = ['apple', 'banana', 'orange']; console.log(fruits[0]); // Output: apple console.log(fruits[2]); // Output: orange

If the index is out of range, JavaScript will return undefined. Meaning that if you try to access fruits[3] in the above example, it will return undefined.

Adding and Removing Elements

One of the most common ways to add a new element to an array is by using the push() method. The push() method adds one or more elements to the end of an array and returns the new length of the array.

For example, to add a new element to the pet array, you can use the following code:

const pet = ['cat', 'dog', 'bunny']; pet.push('parrot'); console.log(pet); // Output: ['cat', 'dog', 'bunny', 'parrot']

To remove the last element of an array, you can use the pop() method. The pop() method removes the last element from an array and returns that element.

For example, to remove the last element from the pet array, you can use the following code:

const pet = ['cat', 'dog', 'tiger']; pet.pop(); console.log(pet); // Output: ['cat', 'dog']

Splicing and Slicing Arrays

One of the more complex methods used with arrays are the splice() and slice() methods:

  • The splice() method changes the contents of an array by removing or replacing an element in the array.
  • The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

For example, to remove the second element from the characters array, you can use the following code:

const characters = ['Bob', 'Pat', 'Ward']; characters.splice(1, 1); console.log(characters); // Output: ['Bob', 'Ward']

The above code removes the second element from the characters array. The splice() method takes two arguments: the index of the element to remove and the number of elements to remove.

To create a new array with the second element from the character array, you can use the following code:

const characters = ['Bob', 'Pat', 'Ward']; const newCharacters = characters.slice(1, 2); console.log(newCharacters); // Output: ['Pat']

The above code creates a new array newCharacters with the second element from the characters array. The slice() method takes two arguments: the index of the element to start the slice and the index of the element to end the slice (not included).


Loops

Now that you have a basic understanding about arrays, let’s talk about loops. Loops are used to execute a block of code multiple times.

While Loops

One of those loops is the while loop. The while loop executes a block of code as long as the condition is true. The syntax of the while loop is as follows:

while (condition) { // code block to be executed }

For example, the following code snippet prints the numbers from 1 to 5:

let i = 1; while (i <= 5) { console.log(i); i++; }

The above code snippet initializes a variable i with the value 1. The while loop executes the block of code as long as the value of i is less than or equal to 5. The value of i is incremented by 1 in each iteration.

For Loops

The for loop is another type of loop that is used to execute a block of code multiple times. The for loop is used when the number of iterations is known. The syntax of the for loop is as follows:

for (initialization; condition; increment/decrement) { // code block to be executed }

For example, the following code snippet prints the numbers from 1 to 5:

for (let i = 1; i <= 5; i++) { console.log(i); }

To iterate over an array using a for loop, you can use the array’s length property. For example, the following code snippet prints the elements of an array:

const arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }

Infinite Loops

An infinite loop is a loop that never ends. This can happen if the condition in the while loop or the for loop is always true. For example, the following code snippet will cause an infinite loop:

while (true) { console.log('Hello, world!'); }
⚠️
Warning

BEWARE of infinite loops! They can crash your browser or your computer. We could demonstrate this here, but… we want you to finish the tech prep work.


Looping through Array Elements

Now that you know about the most common ways to iterate over values and arrays, there are a few more ways to iterate over arrays.

The map() Method

Arrays have a built-in method called map(), which is used to create a new array by applying a function to each element of the original array. The map() method does not change the original array. The syntax of the map() method is as follows:

const array = [1, 2, 3, 4, 5]; const newArray = array.map((arrayValue) => { return arrayValue * 2; }); console.log(newArray); // Output: [2, 4, 6, 8, 10]

The map() method creates a new array by applying the function (arrayValue) => { return arrayValue * 2; } to each element of the original array. This is particularly useful when you want to transform the elements of an array without changing the original array.

While map() may seem like a complex method now, you will see how useful it is when you start working with more complex data structures. It is essential in most modern JavaScript applications.

The filter() Method

One other useful array method is the filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided function. The syntax of the filter() method is as follows:

const numbers = [2, 5, 6, 1, 9, -1] const newNumbers = numbers.filter((number) => { return number > 2; }); console.log(newNumbers); // Output: [5, 6, 9]

Above, the filter() method creates a new array with all elements that are greater than 2. The filter() method does not change the original array.


Other Array Methods and Loops

There are a lot of other array methods and ways to iterate over arrays. Like other topics, you are not expected to know all of them or have their use cases memorized. However, it is important to know that these methods exist for when you need them.

Here are some of the most common array methods:

  • forEach()
  • map()
  • filter()
  • reduce()
  • find()
  • includes()
  • sort()

The final four you are unfamiliar with at this point. Take some time before continuing to do some research on them! Read through available, reputable documentation and examples.