Search⌘ K
AI Features

Manipulating Arrays

Explore the fundamental techniques for manipulating arrays in JavaScript, including adding and removing elements at both ends and modifying values by index. This lesson helps you understand practical array operations to prepare you for more advanced JavaScript coding.

Adding elements to the beginning or end

You can add elements to the beginning and to the end of the array:

  • Push adds elements to the end of the array
  • Unshift adds elements to the beginning of the array
Node.js
let days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.push( 'Saturday' );
console.log("Saturday is added to the end by the push() function\n", days );
days.unshift( 'Sunday' );
console.log("Sunday is added to the beginning by the unshift() function\n", days );

Removing elements

You can also remove these elements from the array:

  • Pop removes the last element from the array and returns it.
  • Shift removes the first element from the array and returns it.
Node.js
let days=['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
//pop
let element = days.pop();
console.log( element, days );
//shift
let secondElement = days.shift();
console.log( secondElement, days );

Similarly to objects, you can delete any element from the array. The value 1 empty item will be placed in the place of this element. You will notice that the length of the array does not change after deleting days[2] because using the delete operator with arrays creates a hole in that place.

Note: It is recommended not to use delete operator to remove an element from JavaScript arrays.

Node.js
let days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
console.log('Length of array days before delete operator: ',days.length);
delete days[2];
console.log(days);
console.log('Length of array days after delete operator: ',days.length);

Overwriting and adding elements at any index

The values of an array can be set by using their indices and equating them to a new value. You can overwrite existing values or add new values to the array. The indices of the added values do not have to be continuous:

Node.js
let days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
days[2] = 'Wednesday';
days[9] = 'Wednesday';
console.log( days );

As with most topics, bear in mind that we are just covering the basics to get you started in writing code. There are multiple layers of knowledge on JavaScript arrays. We will uncover these lessons once they become important.

Technical Quiz
1.

"push and shift are used for the same purpose."

Is the above statement correct?

A.

Yes

B.

No

C.

Not sure


1 / 2