6.2 Adding Elements to an Array

Let's start with an array of two numbers declared as const:

const numbers = [3, 4];

Declaring the variable with const means we can't reassign numbers to a new array, but we are perfectly allowed to modify the existing array's contents. Arrays are objects, so type numbers. and the IDE shows you every property and method available. In this lesson we focus on three methods that add elements: at the end, at the beginning, or in the middle.

push, unshift and splice

  • numbers.push(5, 6) — appends one or more elements at the end of the array.
  • numbers.unshift(1, 2) — inserts one or more elements at the beginning, shifting existing elements to the right.
  • numbers.splice(start, deleteCount, ...items) — inserts elements at any position. start is the index, deleteCount is the number of items to remove (use 0 to only insert), and the remaining arguments are the elements to insert.
numbers.push(5, 6);          // [3, 4, 5, 6]
numbers.unshift(1, 2);       // [1, 2, 3, 4, 5, 6]
numbers.splice(2, 0, "a", "b"); // [1, 2, "a", "b", 3, 4, 5, 6]

Arrays are zero-indexed, so the third element sits at index 2. With splice(2, 0, "a", "b") we go to index 2, remove nothing, and insert "a" and "b". We'll look at removing elements with splice later in this section. See you in the next video about searching for elements.

Summary

This lesson covers three primary methods for adding elements to JavaScript arrays: push() for appending to the end, unshift() for adding to the beginning, and splice() for inserting at specific positions. The lesson emphasizes that while arrays declared with const cannot be reassigned, their content can be freely modified, and explains the parameters required for each method.

Key points

  • The push() method adds one or multiple elements to the end of an array
  • The unshift() method prepends one or multiple elements to the beginning of an array, shifting existing elements to the right
  • The splice() method allows insertion at a specific index with three parameters: start position (index), number of deletions (0 for insertion-only), and the elements to add
  • Variables declared as const cannot be reassigned but their array contents can be modified freely
  • Arrays are objects with built-in methods accessible via dot notation

FAQ

Can I modify an array declared with const?

Yes, const prevents reassignment of the variable itself but allows modification of the array's contents. You can add, remove, or change elements without error.

What is the difference between push() and unshift()?

push() appends elements to the end of the array, while unshift() adds elements to the beginning and shifts all existing elements one position to the right.

How do I use splice() to insert elements without deleting?

Call splice() with three parameters: the start index where you want to insert, 0 for the deletion count (to skip deletion), and the elements you want to add.