Arrays

An Array is an ordered collection of items (Strings, numbers, or other things), array items are indexed from 0 to -1, -1 being the last item of your array, and 0 being the first, that makes the items inside easily accessible.

const cars = ["BMW", "Honda", "Toyota"];
cars[0]; // prints "BMW"
cars[1]; // prints "Honda"
cars[2]; // prints "Toyota"
cars[-1]; // also prints "Toyota"
cars[-2]; // would print the second to last item, in this case "Honda"
// and so on...

Why Use Arrays?

If you have a list of items, storing them in single variables could look like this:

let car1 = "BMW";
let car2 = "Honda"; let car3 = "Toyota";

But, what if you want to loop through the cars and find a specific one? What if you had not 3 cars, but 300? That’s where arrays come in.

An array can hold many values under a single name, and you can easily access them by referring to an index number.

Note: Spaces and line breaks are not important. A declaration can span multiple lines:

const cars = [
"BMW",
"Honda",
"Toyota"
];

You can also create an array, and then provide the elements:

const cars = [];
cars[0]= "BMW";
cars[1]= "Honda";
cars[2]= "Toyota";

Note: You can also create an array with the JavaScript keyword ’new'

const cars = new Array("BMW", "Honda", "Toyota");
// Note: 
// let array = new Array(40) wont work but
// let array = [40] will
// new Array(40) will create an array with a length of 40, instead of populate the array
// with the value 40

You can change an Array element value by using the index number:

const cars = ["BMW", "Honda", "Toyota"];
cars[0] = "Nissan"; // This would change the element in the index 0 to "Nissan"
// "Nissan", "Honda", "Toyota"

Arrays are Objects

Arrays are a special type of objects. The ’typeof’ operator in JavaScript returns “object” for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its “elements”.

const person = ["John", "Doe", 46];
person[1]; // returns "Doe"

Objects use names to access its “members”.

const person = (firstName:"John", lastName:"Doe", age:46);
person.firstName; // returns "John"

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

cars.length // Returns the number of elements
cars.sort() // Sorts the array

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.

When to Use Arrays && When to use Objects

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text).
  • You should use arrays when you want the element names to be numbers.

Useful Built-in Array Methods

Loops

Loops are all about doing the same thing over and over again. Often, the code will be slightly different each time round the loop, or the same code will run but with different variables.

Looping code example

Suppose we wanted to draw 100 random circles on a ‘<canvas>’ element:

const btn = document.querySelector('button');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

document.addEventListener('DOMContentLoaded', () => {
    canvas.width = document.documentElement.clientWidth;
    canvas.height = document.documentElement.clientHeight;
  })

function random(number) {
    return Math.floor(Math.random()*number);
  }

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (let i = 0; i < 100; i++) {
        ctx.beginPath();
        ctx.fillStyle = 'rgba(255,0,0,0.1)';
        ctx.arc(random(canvas.width),
        random(canvas.height), random(50), 0, 2 * Math.PI);
        ctx.fill();
      }
  }

  btn.addEventListener('click', draw);

To accomplish the same without a loop, we would need to repeat the following code for every circle we wanted to draw.

ctx.beginPath();
ctx.fillstyle = 'rgba(255,0,0,0.1)';
ctx.arc(random(canvas.width)),
random(canvas.height), random(50), 0, 2 * Math.PI);
ctx.fill();

Most of the time when you use a loop, you will want to loop through a collection of items, and do something with every one of them.

One type of collection is the “Array”, but there are other ones in JavaScript, including “Set” and “Map”.

The for…of loop

The basic tool for looping through a collection is the for…of loop

const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];

for (const cat of cats) {
    console.log(cat);
  }

The for…of loop in here says:

  1. Given the collection ‘cats’, get the first item in the collection.
  2. Assign it to the variable cat, and run the code inside the curly brackets {}.
  3. Get the next item, and repeat until the end of the collection.

map() and filter()

There are more specialized loops for collections for example: You can use map() to do something to each item in a collection and create a new collection containing the changes:

function toUpper(string) {
    return string.toUpperCase();
  }

const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];
const upperCats = cats.map(toUpper);
console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]

You can use filter() to test each item in a collection, and create a new collection containing only items that match:

function lCat(cat) {
    return cat.startsWith('L');
  }
const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];
const filtered = cats.filter(lcat);
console.log(filtered);
// [ "Leopard", "Lion" ]

filter() will look for boolean values, whatever is evaluated to true will be included, our function returns a boolean value, (true or false). Could also be written like this:

const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];

const filtered = cats.filter((cat) =>
cat.startsWith('L'));
consol.log(filtered);
// [ "Leopard", "Lion" ]

The Standard for Loop

When you don’t want to loop through a collection, like in the “drawing circles” example, and you really just want to run the same code 100 times. In that case you should use the “for” loop.

for (initializer; condition; final-expression) {
    // code to run
  }
  • An initializer – this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.

  • A condition – this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.

  • A final-expression – this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true.

Calculating squares example

const results = document.querySelector('#results');

function calculate() {
  for (let i = 1; i < 10; i++) {
    const newResult = `${i} x ${i} = ${i * i}`;
    results.textContent += `${newResult}\n`;
  }
  results.textContent += '\nFinished!';
}

const calculateBtn = document.querySelector('#calculate');
const clearBtn = document.querySelector('#clear');

calculateBtn.addEventListener('click', calculate);
clearBtn.addEventListener('click', () => results.textContent = '');

Breaking down the for (let i = 1; i < 10; i++) line into its three pieces:

  1. let i = 1: the counter variable, i, starts at 1. Note that we have to use let for the counter, because we’re reassigning it each time we go round the loop.

  2. i < 10: keep going round the loop for as long as i is smaller than 10.

  3. i++: add one to i each time round the loop.

Inside the loop, we calculate the square of the current value of i, that is: i * i. We create a string expressing the calculation we made and the result, and add this string to the output text. So basically we are going:

  1. First iteration i = 1, 1 * 1 = 1.

  2. Second iteration i = 2, 2 * 2 = 4.

And so on, until i = 10 then the loop breaks and the “Finished!” message is shown.

Looping through collections with a for loop

We can also loop through collections with the standard for loop like in the for…of loop example.

const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion'];

for (let i = 0; i < cats.length; i++) {
  console.log(cats[i]);
}

In this loop were starting i at 0, and stopping when i reaches the length of the array. Then inside the loop we’re using i to access each item in the array in turn. This was the standard before for…of existed.

Sometimes you still need to use a for loop to iterate through an array. For example, in the code below we want to log a message listing our cats:

const cats = ['Pete', 'Biggles', 'Jasmine'];

let myFavoriteCats = 'My cats are called ';

for (const cat of cats) {
    myFavoriteCats += `${cat}, `
  }

  console.log(myFavoriteCats); // "My cats are called Pete, Biggles, Jasmine, "

We’d prefer it to handle the last cat differently, like this:

// My cats are called Pete, Biggles, and Jasmine.

But to do this we need to know when we are on the final loop iteration, and to do that we can use a for loop and examine the value of i:

const cats = ['Pete', 'Biggles', 'Jasmine'];

let myFavoriteCats = 'My cats are called ';

for (let i = 0; i < cats.length; i++) {
  if (i === cats.length - 1) {   // We are at the end of the array
    myFavoriteCats += `and ${cats[i]}.`
  } else {
    myFavoriteCats += `${cats[i]}, `
  }
}

console.log(myFavoriteCats);     // "My cats are called Pete, Biggles, and Jasmine."

Exiting loops with break

If you want to exit a loop before all the iterations have been completed, you can use the break statement, the break statement immediately exits the loop and moves on to any code that follows it.

Skipping iterations with continue

The continue statement works similarly to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop.