Essential JavaScript

Adding Elements

We can add elements to an array that already exists.

We use the push and unshift methods to add elements to the beginning or end of the array.

We can use these methods to build an array by adding individual items.

Push to the End

The push method adds an element to the end of the array:

const arr = [1, 2, 3];
arr.push(4);
console.log(arr);

Unshift to the Beginning

The unshift method adds an element to the beginning of the array:

const arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

Array Length

Both of these methods change the number of elements in the array.

The array's length property will automatically update:

const arr = [1, 2, 3];
console.log(arr.length); // 3
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
console.log(arr.length); // 4

Learning Goals

Code Editor