This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Javascript Arrays (creation, basic methods like push, pop, shift, unshift)

In JavaScript, arrays are versatile data structures that can store multiple values in a single variable. They are particularly useful when working with lists or collections of data. Here's an overview of creating arrays and using some basic methods like push, pop, shift, and unshift.

Creating Arrays

There are a few ways to create arrays in JavaScript:

  1. Using Square Brackets ([]):

1let fruits = ['apple', 'banana', 'cherry'];
2

Using the Array Constructor (new Array):

1let numbers = new Array(1, 2, 3, 4, 5);
2

However, the bracket method is more commonly used.

Basic Methods

  1. push() - Adds one or more elements to the end of an array.

1let fruits = ['apple', 'banana'];
2fruits.push('cherry'); // ['apple', 'banana', 'cherry']
3

pop() - Removes the last element from an array and returns it.

1let fruits = ['apple', 'banana', 'cherry'];
2let lastFruit = fruits.pop(); // lastFruit is 'cherry', fruits is now ['apple', 'banana']
3

shift() - Removes the first element from an array and returns it.

1let fruits = ['apple', 'banana', 'cherry'];
2let firstFruit = fruits.shift(); // firstFruit is 'apple', fruits is now ['banana', 'cherry']
3

unshift() - Adds one or more elements to the beginning of an array.

1let fruits = ['banana', 'cherry'];
2fruits.unshift('apple'); // ['apple', 'banana', 'cherry']

These methods are great for managing and manipulating arrays dynamically, especially when you’re working with lists that need frequent updating.