Using Arrays and Loops in JavaScript

Using Arrays and Loops in JavaScript

From declaration to Iteration

·

6 min read

Arrays

What is an Array?

A JavaScript array is an ordered collection of data.

Declaring arrays

JavaScript arrays are enclosed within square brackets with each element within [ and ] separated by a comma. We create an array in the following way:

const personalItems = ['phone', 'wallet', 'keys'];

personalItems is an array containing 3 elements, an element being one of the primitives inside the array. The strings, "phone", "wallet" and "keys" are 3 elements that make up the array personalItems.

Zero indexing

Zero indexing means that we start counting ordered collections of data from zero instead of one. All JavaScript arrays are zero-indexed. We use square bracket notation along with the index position to access specific elements within the array like the following example:

const animals = ['cat', 'dog', 'mouse'];
animals[0]; // evaluates to 'cat'
animals[1]; // evaluates to 'dog'

If you try and access an index that is greater that the number of elements within the array like the following then this will return undefined.

const animals = ['cat', 'dog', 'mouse'];
// only has 3 elements
animals[5]; // evaluates to undefined

.length

One of the most commonly used properties on Arrays is the length property which shows how many elements are inside the Array. As you add or remove elements from the Array this will then update its length. During common usage, you will never normally exceed the maximum amount of elements you can have in an array.

JavaScript arrays can hold elements of multiple data types which makes them very flexible. Due to this, they are said to be mutable as their contents can be altered over time.

const personalItems = ['phone', 'wallet', 'keys'];
personalItems.length; // will be 3

personalItems[3] = 'coins'; // this will insert an item "coins" at index position 3
personalItems.length; // is now 4

Methods

Often we will want to add or take away elements from an array.

JavaScript arrays have inbuilt methods, which is another word for a function, that can be chained onto the arrays themselves

.push() is a method that mutates an array, which means it has been changed from its original state before the method was called on it.

const colours = ['red', 'blue', 'green'];
colours.push('yellow');
// colours is now ["red", "blue", "green", "yellow"];
.pop() also mutates the array it is called upon and removes the last element of the array

const colours = ['red', 'blue', 'green'];
const finalColour = colours.pop(); // finalColour is now 'green'
// colours is now  ['red', 'blue'];
.shift() and unshift() almost work the same way except they add/subtract elements at the beginning of the array.

const colours = ['red', 'blue', 'green'];

// shift to remove an item from the front of an array, and return its value
const firstColour = colours.shift(); // firstColour is now 'red'
// colours is now ['blue', 'green'];

// unshift to add a value to the front of an array
colours.unshift('pink');
// colours is now ['pink', 'blue', 'green'];

You can find all the methods listed in the Arrays MDN Documentation

Nested arrays

You can also have arrays within arrays. For example:

const pokemonGames = [
  ['Red', 'Blue', 'Yellow'],
  ['Silver', 'Gold', 'Diamond'],
  ['Ruby', 'Sapphire', 'Platinum']
];

const bestGame = pokemonGames[1][0]; // 'Silver'

Iteration

Often we'll need to run the same function or piece of code multiple times. Or we'd need to cycle through an array and the elements within it. To do this we'd use iteration, which is another word for loops.

For Loops

For loops allow you to run the same piece of code however ever many times you would like.

We often use For Loops to iterate an array or string and get it to do something to each element within it. In the case of an array, it would be each individual element at that index or position. Then in the case of a string it would be each individual character.

This is an example of a For Loop that will console log each superhero in the superHeroes array.

const superHeroes = ['Batman', 'Superman', 'Aquaman'];
for (let i = 0; i < superHeroes.length; i++) {
  console.log(superHeroes[i]);
}

The initial expression, let i = 0; means that the For Loop will start counting from 0. Because arrays are zero indexed this means the log inside the loop will start from the zeroth element.

The condition expression, i < superHeroes.length; means what condition must be met for the loop to stop. In this case once i = 4 the loop will stop as superHeroes.length === 3.

Lastly you have the increment expression, i++; this means that i will go up by 1 each time.

If I wanted to access the very first index in the names array, outside of using a for loop, we would use square brackets to do this.

We use square bracket notation to access a specific index within the superHeroes array like this:

superHeroes[0]; // 'Batman'
superHeroes[1]; // 'Superman'
superHeroes[2]; // 'Aquaman'
superHeroes[4]; // undefined

The For Loop works in a similar way by accessing each element by its individual index by using the i variable and increasing it incrementally.

You can also use For Loops on numbers and strings.

You can console log every number from 0 to 3.

const numberThree = 3;

for (let i = 0; i <= numberThree; i++) {
  console.log(i);
}

//output
// 0
// 1
// 2
// 3

In this instance we can't use .length because that is only available on arrays and strings.

You can also console.log each character in a string.

const name = 'Neo'
for (let i = 0; i < name.length; i++) {
  console.log(name[i])
}
//output
// "N"
// "e"
// "o"

For ... of Loops

for ... of loops work in the same way but are more readable and go up incrementally without using the i variable. They can be used on arrays and strings alike.

const name = 'Neo'; // would also work with an array of: ['N', 'e', 'o']
let capitalName = [];

for (const letter of name) {
  const capitalLetter = letter.toUpperCase();
  capitalName.push(capitalLetter);
}
console.log(capitalName);
//output
// "['N', 'E' ,'O']"

The 'letter' part within the for ... of loop expression is the name of the element. We could use any word instead of letter and it would still work the same. If you need to loop through an array or string from the first index to the last then the for ... of loop is a good alternative to using a for loop.

Conclusion

Arrays and Loops come up time and time again in JavaScript and are definitely something worth practicing and mastering. One of the best ways I found was through solving small puzzles using them, such as those found on sites like CodeWars. Happy coding!