Skip to content
BetaDE
Lesson 4 of 11JavaScript

JavaScript · Lesson 4 · 30 minutes

Arrays – many values at once

What you'll learn

  • Create arrays and read values by index
  • Add values with push and go through them with for…of
  • Process arrays with filter and map

Creating an array

An array is a list of values in square brackets. As in Python, counting starts at 0:

const animals = ["dog", "cat", "mouse"];
console.log(animals[0]);
console.log(animals.length);
console.log(animals[animals.length - 1]);   // the last one

Adding and going through

const shopping = ["bread"];
shopping.push("milk");
shopping.push("apples");

for (const item of shopping) {
  console.log("-", item);
}

for…of goes through every element – like for item in shopping: in Python.

Good to know: you can change a const array too (with push). const only means the variable always points to the same array.

filter and map

Arrays have built-in tools. The two most important:

  • filter keeps only the elements for which a condition holds.
  • map turns every element into something new.
const numbers = [3, 8, 12, 5, 20];
const big = numbers.filter((n) => n > 6);
const doubled = numbers.map((n) => n * 2);
console.log(big);
console.log(doubled);

(n) => n > 6 is a small function without a name – more about that in the lesson on functions.

Quick check

What does this program print?

const a = [1, 2, 3, 4];
a.push(5);
console.log(a.filter((x) => x > 2).length);

Your task

Your turn

Write two functions. even(numbers) returns a new array with all even numbers. average(numbers) returns the average (total divided by count).

function even(numbers) {
}

function average(numbers) {
}

console.log(even([1, 2, 3, 4, 6]));
console.log(average([2, 4, 9]));

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

function even(numbers) {
  return numbers.filter((n) => n % 2 === 0);
}

function average(numbers) {
  let total = 0;
  for (const n of numbers) {
    total += n;
  }
  return total / numbers.length;
}

console.log(even([1, 2, 3, 4, 6]));
console.log(average([2, 4, 9]));