Jumpstart Your Productivity Using JavaScript Array Splice

javaBuilt-in JavaScript methods can often help you solve many JavaScript programming problems without writing a lot of code. Arrays, like strings, consist of a sequence of items that you can access and update. Arrays may also need rearranging before you can use them to perform certain tasks. Learn to use the array splice method and you can add and remove items from an array using a single line of code. Want to learn JavaScript quickly? Visit Udemy for great tips.

Anatomy of an Array

Think of an array as an empty egg carton that has 12 numbered containers. The carton has no specific use because you can put any type of object into the containers. For instance, if you have 12 marbles, you can drop one marble into each container just as easily as you can drop one penny into each container. JavaScript arrays can hold any type of JavaScript item you can create. While many people use arrays to hold strings and numbers, you can store complex entities such as hyperlinks and objects.

There are several ways to declare and populate an array. The code below shows two of the most common initialization methods:

var array1 = [“A”, “B”,”C”, “D”];
var array2 = [];

The first array has three elements while the second one contains none. You can add and remove elements from either array using a variety of techniques. The push method, for instance, adds a new element to the end of an array and the pop method removes an element from the end of an array as shown below:

array1.push(“E”);
array.pop();

As the JavaScript code on a Web page runs, an array’s contents may change many times. You can check an array’s size anytime by examining its length property, as seen in the following statement:

var arrayLength = array1.length;

Master JavaScript arrays and objects by taking a course at Udemy.com.

Array Splicing Fundamentals

The splice method functions like a powerful “Swiss Army Knife” that gives you the ability to add new array elements and remove existing ones. You can also specify where you want new elements to appear. The splice method’s syntax appears below:

var myArray.splice(start position, number of elements to remove, elements to add);

The first parameter, start position, is the only one required. It specifies the location in the array where you want your add and remove operation to begin. The second optional parameter represents the number of elements to remove from the array.  If that value is zero, splice doesn’t remove any elements. The third optional parameter is a list of items you’d like to add to the array.

When you only specify the first parameter, slice removes all elements starting at that position all the way to end of the array. If the first argument is negative, splice adds or removes elements starting at the end of the array.

Splice Syntax and Examples

Because so many different combinations of parameters exist, it’s important to understand how the splice method affects an array when you use the method. One way to do that is to write a short JavaScript program that calls splice in different ways, as shown below:

var grades = [99, 84, 76, 100, 70];
grades.splice(3));             /* Removes 3rd element and all elements after it */
grades.splice(1, 2));          /* Removes elements in positions 1 and 2 */
grades.splice(2, 1, 55));      /* Removes element 2 and adds new element 55 after element 2 */
grades.splice(-1, 0, 88, 92);  /* Removes no elements because second argument is zero. */
                               /* It adds 88 and 92 as new elements starting from the 1st position from the array's end.*/

If you add an alert(grades) statement after each splice statement, you’ll see the values in the grades array after each splice. Things get a little tricky when you specify negative numbers as your first argument. Don’t forget that splice starts counting from the array’s end when the first argument is negative, as seen in the last example above.

Always use zero as your second argument when you don’t want splice to remove any array elements. This value comes in handy when you only wish to add new elements to the array by specifying then as the third parameter.  Review this example again:

grades.splice(-1, 0, 88, 92);

Even though the splice command’s syntax says that it accepts three parameters, the third parameter can be a list of comma separated values as shown above. The values 88 and 92 make up that third argument. If you only wanted to add a new value to the array, you’d only see one value as the third parameter, as shown below:

grades.splice(-1, 0, 88);

Use Splice to Create New Arrays

Another important thing to understand about the splice method is the way it returns values. The previous examples, simply use splice to alter an existing array. However, you can create a new array that contains elements that splice removes from another array by using the following code:

var grades = [99,44,33,83,100];
var newArray = grades.Splice(1, 2);

alert(grades);

alert(newArray);

Splice removes 2 elements from the grades array starting at the first position so that array only contains 99, 83 and 100 after the code runs. The newArray, however, contains 44 and 33, the elements removed from the grades array. By using this type of assignment statement, you can modify an existing array, such as grades and generate a new one using a single statement.

Slice Vs. Splice: Important Differences

Similar to splice, the slice method manipulates an array’s elements. While splice changes an existing array, slice creates a new array without altering the original. Using slice is similar to taking a snapshot of part of an existing array and storing that snapshot in a new array. Consider the following code:

var values = [101, 37, 16, 88];

Suppose you wanted to create a new array that only contained elements 1 and 2? You could do that by defining an empty array and using the push method to add new elements to it. Or, you could save time by using the slice method to copy the elements you want from the values array into your new array, as seen in the following example:

var newArray = values.slice(1, 3);

The newArray array contains 37 and 16 after the code runs because slice starts grabbing elements in position 1 and ends before it gets to position 3. In other words, it copies 37 and 16 and puts them into newArray. Here’s the slice method’s syntax:

myArray.slice(begin, end);

The value you pass as begin tells slice where to begin copying elements. The value you pass as end is always one position to the left of the last element you want slice to copy. The end parameter is optional. If you don’t include it, slice copies all elements from the beginning position all the way to the end of the array. As with the splice method, slice begins selecting elements from the end of an array if you specify a negative value as the first argument.  Need tips on improving your JavaScript coding? Let Udemy help you.

JavaScript Array Splicing: Conclusions

Although the splice and slice methods are simple, review their syntax several times before trying to use either one in a production environment. It takes a bit of practice to learn how each parameter, whether positive or negative, affects your original array and new arrays you create using splice or slice. However, once you master these important methods, you’ll discover new ways to manipulate arrays and handle complex JavaScript tasks more efficiently.