codecks.

Arrays & objects · Output question

JavaScript filter and a later push

A filtered array gets another element. Predict which values appear in the original and the filtered array.

const scores = [2, 5, 8];
const passed = scores.filter(x => x > 3);
passed.push(11);
console.log(scores.join(","));
console.log(passed.join(","));

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. 2,5,8,11
    5,8,11
  2. 5,8
    5,8,11
  3. 2,5,8
    5,8,11
  4. 2,5,8
    5,8
Reveal the answer and execution trace
2,5,8
5,8,11

filter returns a new array. Appending a number to passed leaves the original scores array alone.

  1. Line 2. The matching values 5 and 8 are collected in a new array.
  2. Line 3. 11 is appended to passed.
  3. Line 4. scores still contains all three original numbers.
  4. Line 5. passed now contains 5, 8, and 11.

Reference: Array filter on MDN.