Skip to content

Incorrect Array Method

Quick summary

You used the wrong array method — splice mutates while slice copies, forEach returns undefined while map returns a new array.

Why this happens

  • Confusing slice (copy) with splice (mutate)

  • Using forEach when you need map (or vice versa)

  • Confusing find (first match) with filter (all matches)

Minimal example

✗ Broken code
const arr = [1, 2, 3, 4, 5];
const result = arr.splice(1, 2); // Mutates arr!
console.log(arr); // [1, 4, 5] — original changed!
console.log(result); // [2, 3]
✓ Fixed code
const arr = [1, 2, 3, 4, 5];
const result = arr.slice(1, 3); // Does NOT mutate
console.log(arr); // [1, 2, 3, 4, 5] — original intact
console.log(result); // [2, 3]

splice modifies the original array and returns the removed elements. slice returns a copy of a portion without modifying the original. Using slice when you do not want to mutate is the correct choice.

How to diagnose

  • Check if the original array was unexpectedly modified

  • Verify the return value matches what you expect

  • Read the method documentation to confirm its behavior

How to fix

  • Use the correct method for your intent (slice to copy, splice to modify)

  • Use map when you need a new array, forEach for side effects

  • Use find for one result, filter for multiple results

How to prevent

  • Review array method documentation before use

  • Test with small arrays to verify behavior

Related Resources

Related Glossary

Related Lessons

  • Arrays

    Learn about array methods.

← Back to language