Splice Together Explainer


Aim of the puzzle: Use the .splice() array method to insert or replace elements in an array.
Walk through of solution: The .splice() method is a useful and flexible way to add or replace elements anywhere in an array.

Splice takes 3 arguments when it is called:

  1. The index number where to insert
  2. The number of items to replace
  3. The new items to insert

In this puzzle, the numbers array begins with 3 elements, the numbers 1, 3, and 4. To add the number 2 into the 2nd position, splice is used like this:

numbers.splice(1, 0, 2);

In the above code, 1 is the index position where we want to insert the new element. 0 is the number of items to replace, and 2 is the new element.
Sample code solution:

let numbers = [1, 3, 4];

numbers.splice(1, 0, 2);

Javascript Concepts: Arrays, Array Methods, .splice(), Variable Declarations with Let, console.log