QUESTION 10 / 20 · ARRAYS · BEGINNER

Keep the even ones

What will this code print? Read each line, then make your prediction.

Where this matters

Filter selects existing items that satisfy a condition, such as keeping only available products. It does not replace them with the condition results.

JavaScript · read-only example
console.log(JSON.stringify([1, 2, 3, 4].filter(n => n % 2 === 0)));
Your prediction

Read the full explanation

Filter retains the original elements whose predicate is true. Two and four have remainder zero when divided by two.

Trace the code

  1. The predicate produces false, true, false, true for the four entries.
  2. Filter keeps the input entries at the true positions.
  3. The order of the retained entries matches their original order.

Why the other predictions differ

  • [false,true,false,true] — Those are predicate outcomes, not the elements returned by filter.
  • [1,3] — Odd numbers have remainder one and fail this predicate.
Expected console output
[2,4]

Reading this explanation does not record mastery. A correct submitted attempt can do so, including after review.

Change one thing

Use map with the same predicate to see the boolean results themselves.

Predict the result, then run this self-contained snippet in your browser’s developer console. It uses only sample values and makes no network requests.

console.log(JSON.stringify([1, 2, 3, 4].map(n => n % 2 === 0)));
Check the variation’s output
[false,true,false,true]

Explain which binding, value, or operation changed before moving to the next challenge.