DEV Community

Cover image for Understanding Arrays in JavaScript
Sophia Li
Sophia Li

Posted on • Originally published at

Understanding Arrays in JavaScript

Photo by MIKHAIL VASILYEV on Unsplash

An array in JavaScript is an ordered collection of data.

Arrays are ordered by numbered indices starting at 0. These indices are used to access elements in arrays. Arrays help condense and organize our code because they allow us to store multiple values in one variable. This means arrays contain values that we can iterate (loop) over.

Arrays are mutable, which means we can add, remove, and modify array values. Arrays can hold different types of data such as numbers, strings, objects, booleans, etc.

In this blog, we'll go over:

  • How Arrays Help Consolidate Code
  • Creating Arrays
  • Indexing Arrays
  • Accessing Items in Arrays
  • Finding the Length of Arrays
  • Adding Items to Arrays
  • Removing Items in Arrays
  • Modifying Items in Arrays
  • Looping Through Arrays

How Arrays Help Consolidate Code

Let's take a look at how arrays help us condense and organize code.

In the following example, we assign three different animals to three different variables. If we want to store more animals, we'd have to declare and initialize each animal one by one. That would get tedious and difficult to keep track of pretty quickly.

const animal1 = 'cat'
const animal2 = 'panda'
const animal3 = 'sloth'

We can instead consolidate all of our animals into an array called animals. In the example below, we have one variable, animals, with three elements, cat, panda, and sloth.

let animals = ['cat', 'panda', 'sloth']

Creating Arrays

There are two ways to create an array:

  1. Bracket notation using []
  2. Array constructor using the new keyword

Both bracket notation and the constructor method create an array.

Let's take a look at both methods.

First, let's use brackets [] to create the animals variable, an array containing the elements, cat, panda, and sloth. We can print animals in the console to show the array of animals, ["cat", "panda", "sloth"].

let animals = ['cat', 'panda', 'sloth']

// ["cat", "panda", "sloth"]

Next, let's use the new keyword to create the animals variable, an array containing the elements, cat, panda, and sloth. The result of using the new keyword is the same as using brackets [].

let animals = new Array('cat', 'panda', 'sloth')

// ['cat', 'panda', 'sloth']

Bracket [] notation is the prefered and easier way to create an array because the constructor method can lead to unintended outcomes. For example, when working with numbers.

If we want to put the integer 3 in an array using the constructor method, it'll give us three undefined elements instead of [3].

let numberOfAnimals = new Array(3)

// [undefined, undefined, undefined]

If we want to put the integer 3 in an array using bracket syntax, we get what we expected, [3].

let numberOfAnimals = [3]

// [3]

Arrays can also hold more than just strings. Arrays can hold different types of data such as numbers, strings, object, etc.

let pets = ['cat', 2, 'panda', 1, 'sloth', 8, { cute: true }]

Indexing Arrays

Elements in arrays are ordered sequentially by indexes. Each element in an array has an index. Indexes are integer values starting from 0.

Let's revisit our animals array again.

let animals = ['cat', 'panda', 'sloth']

Here's what our animals array looks like with their respective indexes:

cat panda sloth
0 1 2
  • cat is the 1st element in the array, and cat's index is 0.
  • panda is the 2nd element in the array, and panda's index is 1.
  • sloth is the 3rd element in the array, and sloth's index is 2.

To find the index of a certain element, we use the indexOf method. indexOf returns the first index where the element is found, or returns -1 if the element is not found.

Here, we use indexOf to find the index of 'panda' in our animals array.

// Print the index of 'panda', 1
// 1

// Print -1 because 'dragon' is not in the `animals` array
// -1

Accessing Items in Arrays

Arrays are ordered elements with indexes.

To access an element, we put the index number inside brackets [] after the variable name. The syntax looks like this, variableName[indexNumber].

For example, to access the first element, we use the syntax, variableName[0].

Let's take a look at this in action. To access the first element, cat, in animals, we use the syntax, animals[0].

let animals = ['cat', 'panda', 'sloth']

// 'cat'

// 'panda'

// 'sloth'

If we try to access an index that doesn't exist, we get undefined. In this example, index 4 doesn't exist, so undefined is printed when we try to access animals[4].

let animals = ['cat', 'panda', 'sloth']
// undefined

Arrays can also be nested, meaning an array can be stored within an array. Just like before, we access elements in nested arrays with the syntax variableName[indexNumber], but with an additional [indexNumber] to access the index within the initial array. So the syntax for accessing an element in an array within an array looks like this, variableName[indexNumber][indexNumber].

Let's take a look at this nested array, nestedAnimals.

let nestedAnimals = [
  ['blue whale', 'blue jay'],
  ['red panda', 'red ants', 'red fox'],

Before we write the code to access and print out some animals, let's break down what the indexes are.

Here's the first level elements with their respective indexes.

["blue whale", "blue jay"] ["red panda", "red ants", "red fox"]
0 1

We can go a level further and break each index down so each element in the array has its own index.

"blue whale" "blue jay"
0 1
"red panda" "red ants" "red fox"
0 1 2

Now let's take a look at the code and print out 'blue whale'. 'blue whale' is in the array of index 0 of nestedAnimals. Index 0 contains the array ["blue whale", "blue jay"],. 'blue whale' is index 0 of index 0. So to access 'blue whale', we use the syntax, nestedAnimals[0][0].

The same applies for 'red ants'. 'red ants' is in index 1 of index 1's array. So nestedAnimals[1][1] accesses 'red ants'.

// Print the 0th index of the 0th index
// 'blue whale'

// Print the 1st index of the 1st index
// "red ants"

Finding the Length of Arrays

To find the length of an array, we use the length property.

Here, we use the length property on animals to get a length of 3.

let animals = ['cat', 'panda', 'sloth']

// Print the length of animals
// 3

Adding Items to Arrays

To add an item to the end of an array, we use the push method.

// Append 'sea otter' to the end of the array
let animals = ['cat', 'panda', 'sloth']
animals.push('sea otter')

// ['cat', 'panda', 'sloth', 'sea otter'];

To add an item to the beginning of the array, we use the unshift method.

// Append 'koala' to the beginning of the array
let animals = ['cat', 'panda', 'sloth']

// ['koala', 'cat', 'panda', 'sloth',];

We can also specify which index we want a new element to be added to by using the assignment = operator. If the index of the new element is greater than the length of the array, undefined will be added until the specified index is reached.

// Append  'zebra' to index 6 of the array
let animals = ['cat', 'panda', 'sloth']
animals[6] = 'zebra'

// undefined is appended until we hit index 6, where we append 'zebra'
// ['cat', 'panda', 'sloth', undefined, undefined, undefined, 'zebra'];

If we set the length to a size larger than the array, it'll append values of undefined to the end of the array until it hits the new length.

// Append undefined two times to the end of the array until the length is 5
let animals = ['cat', 'panda', 'sloth']
animals.length = 5

// ['cat', 'panda', 'sloth', undefined, undefined]

Removing Items in Arrays

To remove the last element in an array, we use the pop method.

// Remove the last element, 'sloth'
let animals = ['cat', 'panda', 'sloth']

// ['cat', 'panda'];

To remove the first element of an array, we use the shift method.

// Remove the first element, 'cat'
let animals = ['cat', 'panda', 'sloth']

// ['panda', 'sloth']

To remove an element by index position, we use the splice method. The first parameter specifies the index where we should start removing, and the second paramater specifies how many elements we should delete.

In this example, splice mutates the animal array. It removes one element at index 1. so 'panda' is removed. The array now only contains 'cat' and 'sloth'.

// Remove 1 element at index 1, 'panda'
let animals = ['cat', 'panda', 'sloth']

animals.splice(1, 1)

// ['cat', 'sloth']

To remove an element by index position without mutating the original array, we can use slice. The first parameter specifies the start and the second parameter specifies the end. The end is exclusive because the end index is not included.

// Remove 1 element at index 1, and end at index 2 (index 2 is not included)
let animals = ['cat', 'panda', 'sloth']
let slicedAnimal = animals.slice(1, 2)
// 'panda'

// Animals is not mutated
// ["cat", "panda", "sloth"]

Another way to remove elements is to set the length of the array to a lesser value.

// Set length to 2, which removes 'sloth'
let animals = ['cat', 'panda', 'sloth']
animals.length = 2

// ['cat', 'panda']

Modifying Items in Arrays

To modify an element's value in an array, we specify the index inside brackets [] and the assignment = operator to assign an updated value. The syntax looks like, variableName[indexToModify] = 'newValue'.

// Modify the value of index 0 ('cat') to 'dog'
let animals = ['cat', 'panda', 'sloth']
animals[0] = 'dog'

// ['dog', 'panda', 'sloth']

We can also modify a value using the splice method. The first parameter specifies which index we should start modifying, the second parameter specifies how many elements we should remove, and the third and further parameters specifies what element(s) we should add.

// Replace 1 element at index 2 ('sloth') with 'wolf'
let animals = ['cat', 'panda', 'sloth']
animals.splice(2, 1, 'wolf')

// ['cat', 'panda', 'wolf']
// Replace 1 element at index 1 ('panda') with 'wolf' and 'lion'
let animals = ['cat', 'panda', 'sloth']
animals.splice(1, 1, 'wolf', 'lion')

// ['cat', 'wolf', 'lion', 'sloth']

Looping Through Arrays

We can loop through an array using a for loop. To loop through an entire array, we can use the length method to easily determine how many times we should loop.

In this example, we loop through the array and print each element to the console.

let animals = ['cat', 'panda', 'sloth']

for (let i = 0; i < animals.length; i++) {

// output:
// cat
// panda
// sloth

The for...of statement also loops over arrays.

Similar to above, in this example, we also loop through the array and print each element to the console. The syntax using a for...of loop is shorter and cleaner.

let animals = ['cat', 'panda', 'sloth']

for (let i of animals) {

// output:
// cat
// panda
// sloth


In this blog, we learned:

  • How arrays help condense and organize code.
  • How to create arrays using bracket [] notation (the preferred method) and array constructors.
  • How arrays are indexed starting at 0.
  • How to access items using [indexNumber].
  • How to find the length of an array using the length method.
  • How to add items using push, unshift, the = operator, and the length method.
  • How to remove items using pop, shift, splice, and slice.
  • How to modify items using the = operator and splice.
  • How to loop through arrays using for and for...of loops.

Arrays are a fundamental part of programming in JavaScript. You now know how to work with them!

Originally posted on

Discussion (11)

andrematias profile image
André Matias • Edited on

It was a beautiful post about arrays.
I know, that was in JS.
I came from python and I'm learning JS now. Your post was a good explanation about arrays.
But, I have a question, if you could help me it'll be wondefull.
In python we have tuples, tuples are objects like arrays, but are immutables, I cannot push a new element to inside of instance.
In JS, does it possible to do the same?
I was thinking that I could change the prototype object of an array and block the methods that is responsible to do that.
I don't know if in JS there is some object immutable, and don't know if change the prototype is a good aproach nowadays.
Just to know, noob questions hehe.

sophia_wyl profile image
Sophia Li Author

Thanks! It's been a while since I've used Python, so I can't speak to any comparisons between JavaScript and Python.

But if your question is, can you push an item to the end of an array in JavaScript? Then answer is yes. There are various ways to do it. One of them is using the "push" array method. I write about how to use array methods here:

andrematias profile image
André Matias • Edited on

Ok, thanks, I'll read that.
In truth, my doubt is if I can block methods like push, just to denied input elements into an array after I created one instance.
I'll search on google and study more, but thank you any way.

Thread Thread
thefern profile image
Fernando B 🚀

Hi there, yes you can make an array immutable by calling the Freeze function after you've initialized the array. Or probably easier just to make it a constant variable. Also have a look here

Thread Thread
andrematias profile image
André Matias

Thank you.

fkrasnowski profile image
Franciszek Krasnowski

Look for Object.seal. It does block object from adding new elements to it, but you can still change the existing property values, as opposed to Object.freeze:

const array = [1, 2, 3];
array.push(2) // TypeError: object is not extensible

array[0] = 5; // array = [5, 2, 3]
andrematias profile image
André Matias

Excellent, Thanks dude.

athomsfere profile image
Austin French

I'd probably also mention for why to use an array: performance.

Javascript is really "dumb". On the wire, and by processing power the amount of time between between:

const animal1 = 'cat'
const animal2 = 'panda'
const animal3 = 'sloth'


let animals = ['cat', 'panda', 'sloth']

is over 40%, before any minification / uglification.

assuming a decent webpack/ minification:

  let a=['cat', 'panda', 'sloth']


const a='cat'
const b='panda'
const c='sloth'

we still save ~30% on the payload, and likely in the browsers processing time of the script.

Which while it doesn't matter for 1-3 lines of code, it certainly does over hundreds, or thousands of lines especially when the user is on a phone on 3G paying for international data roaming...

hemant profile image
Hemant Joshi 😼

I love these kind of quick Posts which are really informative and helpful and it takes no time to go through and usually end of with saving to reading list🙃...

Thanks for being so so so much awesome and helpful.


Really good post on Arrays...

mohsenalyafei profile image
Mohsen Alyafei

Thank you. Very nice article.

adlo777 profile image