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:
Using Square Brackets (
[]
):
let fruits = ['apple', 'banana', 'cherry'];
Using the Array Constructor (new Array
):
let numbers = new Array(1, 2, 3, 4, 5);
However, the bracket method is more commonly used.
Basic Methods
push()
- Adds one or more elements to the end of an array.
let fruits = ['apple', 'banana'];fruits.push('cherry'); // ['apple', 'banana', 'cherry']
pop()
- Removes the last element from an array and returns it.
let fruits = ['apple', 'banana', 'cherry'];let lastFruit = fruits.pop(); // lastFruit is 'cherry', fruits is now ['apple', 'banana']
shift()
- Removes the first element from an array and returns it.
let fruits = ['apple', 'banana', 'cherry'];let firstFruit = fruits.shift(); // firstFruit is 'apple', fruits is now ['banana', 'cherry']
unshift()
- Adds one or more elements to the beginning of an array.
let fruits = ['banana', 'cherry'];fruits.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.