JavaScriptLesson 7 of 10Jump to practice

Arrays

Work with lists of values: add and remove items, search them, and transform them with map and filter.

An array is an ordered list of values. You met arrays in the variables lesson. Now let’s do things with them.

const fruits = ["apple", "banana", "pineapple"];
//  index:         0         1          2

Adding and removing

Method What it does
push(x) Add x to the end
pop() Remove the last item (and give it back)
unshift(x) Add x to the start
shift() Remove the first item
Changing an array
Open in editor
<script>
const queue = ["Emma", "Diego"];

queue.push("Sofia");
console.log("After push:", queue);

const served = queue.shift();
console.log("Served:", served);
console.log("Still waiting:", queue);
console.log("How many:", queue.length);
</script>
Result

Searching

  • includes(x) gives true or false.
  • indexOf(x) gives the position, or -1 if it isn’t there.
  • find(fn) gives the first item that passes a test.

Transforming: map, filter and forEach

These three take a function and run it on every item. They replace most loops.

Method Gives you
forEach(fn) Nothing. Just runs fn on each item
map(fn) A new array, with each item changed by fn
filter(fn) A new array, with only the items where fn returns true
map and filter
Open in editor
<script>
const prices = [40, 250, 90, 120, 60];

const halfOff = prices.map((p) => p / 2);
console.log("Half off:", halfOff);

const cheap = prices.filter((p) => p < 100);
console.log("Under 100:", cheap);

const total = prices.reduce((sum, p) => sum + p, 0);
console.log("Total:", total);

prices.forEach((p, i) => console.log("Item " + i + " costs " + p));
</script>
Result

map and filter never change the original array. They hand you a new one.

Joining into text

join() turns an array into one string:

["HTML", "CSS", "JavaScript"].join(", "); // "HTML, CSS, JavaScript"

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Add "grape" to the end of the array.

    const fruits = ["apple", "banana"];
    fruits.("grape");

  2. Exercise 2

    Check whether the list contains "apple" (gives true or false).

    console.log(fruits.("apple"));

  3. Exercise 3

    Keep only the prices under 100.

    const prices = [40, 250, 90, 120];
    const cheap = prices.((p) => p < 100);

Quiz: 3 questions

1. What does [10, 20, 30].map((n) => n * 2) give?
2. What does pop() do?
3. An array has 5 items. What is the index of the last one?

Finish the practice to complete this lesson.

Sign in to keep your progress on any device.