toolqik

206 · JavaScript

JavaScript Array Methods Playground

Try map, filter, reduce, sort and every other array method, and see each callback step.

Runs in your browser

Code

  
Result

  
Original array afterwards

  

About this tool

Pick an array method, edit the array and the callback, and press Run to see what the method returns, what the original array looks like afterwards, and every call the method made to your callback with its arguments and return value. It’s a quick way to learn the array API or check an edge case before writing it into your code.

Mutating and non-mutating methods

Some methods change the array they’re called on: sort, reverse, splice, fill, push and friends. That surprises people when the array is shared, for example in React state. The playground shows the original array after each call and marks mutating methods. Each has a copying twin added in ES2023: toSorted, toReversed, toSpliced and with.

Common pitfalls the trace makes visible

  • sort() without a compare function sorts as strings, so [10, 9, 1] becomes [1, 10, 9].
  • reduce without an initial value uses the first element as the accumulator and skips calling back for it.
  • find and some stop at the first match, so later elements are never visited.
  • forEach always returns undefined; use map when you need the results.

Safe to run

Your code runs in a Web Worker inside a sandboxed iframe with its own unique origin. It can’t read this site’s storage or cookies or touch the page, and an infinite loop can always be stopped, because the worker is terminated rather than asked to stop.

FAQ

What is the difference between map and forEach?

map returns a new array of the callback’s return values; forEach returns undefined and is only for side effects.

Why does sort put 10 before 9?

Without a compare function, sort converts elements to strings and compares them as text. Use (a, b) => a - b for numbers.

Which array methods change the original array?

sort, reverse, splice, fill, copyWithin, push, pop, shift and unshift. toSorted, toReversed, toSpliced and with return copies instead.

What does reduce do?

It walks the array carrying an accumulator: each callback receives the accumulator and the current element and returns the new accumulator. The final accumulator is the result.

Is my code run safely?

Yes. It runs in a sandboxed Web Worker that can’t access this page, and it’s stopped if it takes too long.

esc
↑↓ navigate↵ open