Skip to main content

Command Palette

Search for a command to run...

Beginners Guide To JavaScript Arrays

All you need to know to get started with JavaScript arrays. Indexes, Push, Pop, Shift, Unshift and more.

Updated
8 min read
Beginners Guide To JavaScript Arrays

What is an Array?

It is an extremely important data structure not just in JavaScript but also in many other programming languages. Arrays let us store list of values in a single variable that's in order, can be mutated and more importantly iterated through.

How to create an array?

Before we discuss about how to create an Array let's start by asking the question why do we need an array in the first place.

Let's assume you have a few hobbies, "Gardening", "Fishing", "Gaming". Now, if you want to store them in your program you have two choices. You can store each of your hobbies in a separate variable.

let hobby1 = "Gardening"
let hobby2 = "Fishing"
let hobby3 = "Gaming"

The second option would be to store them all inside of a single Array which is the preferred way.

let hobbies = ["Gardening", "Fishing", "Gaming"]

So, what's the problem with creating separate variables? In the programming world actually it's pretty obvious. Let's understand this.

Assume you've developed a new hobby over the time, then you have to come back to your code and declare a new variable and store your precious new hobby. And you have to do the same every time you develop a new hobby. Meaning you're repeating the same thing again and again.

Okay, I hope everyone understands why we need arrays now.

So, how do we actually create an array? Well, there are a few different ways you can but we're going to discuss the most basic way to do so which is using a [] as we've already seen in the previous code snippet.

There our array already had a few values inside. So, if you're planning on creating an empty array you can do so by:

let myArray = [];

Okay, finally we know how to create an array in javascript.

Now we've seen how to create an array with and without values but how do we add or remove a value from an existing array? We have a few simple methods to do that.

Array push(), pop(), shift(), unshift()

Wait, wait, wait a minute!🤚 Before we try to understand about those pretty interesting methods let's get to know a few other important topics related to Arrays: Array length and Array index.

Note: You can store any datatype in arrays, it can be String, number, other arrays, objects etc. And because of JavaScript's extremely dynamic and forgiving nature we can mix match datatypes in Arrays.

let myArray = ["Programming", 106, ["Hi guys"], {name: "Alex"}]

console.log(myArray)

If you've not notice I've stored String, number, another array and even an object inside of the array myArray. It is completely valid in JavaScript.

Array Length

So, what does length mean? I hope everyone understands what length means in plain English. So, what does it mean in programming?

The number of elements in an Array is the length of that particular Array.

Let's see a few examples.

let numbers = [5, 9, 3, 4, 6, 2];

For the above Array length is 6.

let hobbies = ["Gardening", "Fishing", "Gaming"]

For the above Array length is 3.

So, what would be the length for an empty Array? It's 0(zero).

let hobbies = []

For the above Array length is 0.

So, how do we calculate the length of an array? Mostly we don't calculate the length ourselves because in JavaScript the length is already there as a property in the Array. To get the value we simply use the length property.

let hobbies = ["Gardening", "Fishing", "Gaming"]

console.log(hobbies.length)

The above snippet prints 3 in the console. So, the .length property is going to return the length of that particular Array at that time.

Array Index

Okay, enough of this Array length. Let's talk about another extremely important topic for Array, index. So, what is an index? The index in array refers to the the position of an element in an array.

Let's say you're living in a shared apartment. You have your own room and that room has a room number. So, you and the other residents in the apartment are the elements and the room numbers are the index. So, if I have to go to your room I can do so by only knowing the apartment name(variable) and the room number(index) you are living in instead of going to every room looking for you.

The maximum Index number in an array will be (length of an Array - 1). Simply because they start from 0(zero). Meaning index numbers in Array is zero based.

let fruits = ['Banana', 'Apple', 'Orange', 'Pineapple'];
// Index :       0         1         2          3

Here, the length of our Array is 4. So, the maximum the index number can go upto is 3(length of Array - 1). So, what are the index numbers for our array elements?

Indexing elements starts from the first element in an array from the left, so in our example Banana is the first element and as I said before the index number starts from 0(zero). So, the index for banana is 0.

Then index number is incremented by 1 for every next element in the Array. So, the other index numbers are: Apple = 1, Orange = 2, Pineapple = 3.

As we can see the index number stopped at pineapple with 3 which is the last element in the Array. So, we can conclude(I'm the only one 😔 making these conclusions) whatever I said earlier was true.

Oh boy, a lot of things are here. If you feel overwhelmed please feel free to take s break and come back later. 😉

Arrays work in LIFO order

So, what does it mean? Specifically what does LIFO means.

LIFO = Last In, First Out

Don't worry it's just a fancy term in programming that means the item that gets in the array last is the first item that can get out of it. Meaning, we can only add and remove elements from the end on an Array.

For now, just know this term we'll explore and see examples in detail very soon.

Now, comes the interesting part 😉. How to mutate an Array? Specifically, how to add or remove elements from an array?

Array push() Method

Using the Array push() method we can add an element at the very end of an Array.

It follows the LIFO principle.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

hobbies.push('Fishing')

console.log(hobbies)

This is going to add Fishing at the end of the the hobbies Array and mutate it into:

['Cycling', 'Gardening', 'Swimming', 'Fishing']

Easy right? 😁

Array pop() Method

Array pop() method does the exact opposite of our previous method Array push(). Meaning it removes the last element from an Array.

It follows the LIFO principle.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

hobbies.pop()

console.log(hobbies)

The above snippet will remove Swimming from the end of the hobbies Array and mutate it into:

['Cycling', 'Gardening']

Also, the Array pop() method returns the element it removed from the Array.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

let removedHobby = hobbies.pop()

console.log(removedHobby)

The above snippet will print Swimming in the console.

Pretty Interesting right? I know. If for some reason if you think it's too much just take a break and come back to it later.

Now, we're going to look at two more methods related to Array.

Array unshift() Method

The Array unshift() works similar to the Array push() method but the main difference is: it adds the element to the front of the Array instead of the end.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

hobbies.unshift('Fishing')

console.log(hobbies)

The above code snippet will add Fishing at the front of the the hobbies array and mutate it into:

['Fishing', 'Cycling', 'Gardening', 'Swimming', 'Fishing']

As expected the Array .unshift() method has added the element to the front of the hobbies Array.

Note: It might look very tempting to use this method to insert an element to the front of an array but it's not recommended at all as it affects the performance of our code.

Array shift() Method

Well Array shift() does everything every similar to the previous Array pop() method but it removes the element from the front of the Array.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

hobbies.shift()

console.log(hobbies)

This will remove Cycling from the front of the the hobbies array and mutate it into:

` ['Gardening', 'Swimming']

When we useArray shift()it returns the removed element from the array just as theArray pop()` does.

let hobbies = ['Cycling', 'Gardening', 'Swimming']

let removedHobby = hobbies.shift()

console.log(removedHobby)

The above code snippet will print Cycling to the console.

Note: Just as the Array unshift() this Array shift() is not recommended to use as it costs quite a bit of performance in our code.

Retrieve Element From a Specific Index

We first have to know the position of the value or to be precise the Index number of the element we want to retrieve from the Array. Then we attach the [] to the variable name and inside we pass the Index number of our desired element.

let hobbies = ['Cycling', 'Gardening', 'Swimming']
// Index :         0           1            2

let hobby = hobbies[1];
console.log(hobby);

The above code snippet will print Gardening in the console which is the second element in our Array as we passed 1 inside the [].

The index number starts from zero, remember?