DEV Community

Cover image for JavaScript Tutorial Series: Arrays
The daily developer
The daily developer

Posted on • Updated on

JavaScript Tutorial Series: Arrays

We've previously seen how to store a value inside a variable. In this post we're going to learn how to store multiple values in one variable.

What is an array ?

An array is a variable that can hold multiple values.

How to declare an array ?

To declare an array we start by giving it a name and followed by an equal sign and two square brackets.

let animals = [];
Enter fullscreen mode Exit fullscreen mode

The code above denotes an empty array. The word array is a reserved keyword in JavaScript which means you cannot name your variable array.

let animals = ["dog", "cat", "duck", "penguin"];
Enter fullscreen mode Exit fullscreen mode

We can give entries to our array as you see in the example above. The entries we provided are strings that are comma separated. The arrays can hold multiple types such as numbers, strings and booleans.

How to access the data in an array?

In the last post we've seen that we can access a string using bracket notation which use zero-based indexing. Arrays work the same way.

So Since Arrays are similar to strings, meaning arrays use zero-based indexing. The first element of an array has an index of 0.

let animals = ["dog", "cat", "duck", "penguin"];
console.log(animals[0]); //dog
Enter fullscreen mode Exit fullscreen mode

You can also modify an array using indexes like so:

let animals = ["dog", "cat", "duck", "penguin"];
animals[0] = "bird"
console.log(animals[0]); //bird
Enter fullscreen mode Exit fullscreen mode

Nesting an array into another

You can nest an array into another. This is called a multi-dimensional array, and it is done like so:

const numbers = [
 [10,11],
 [9,5],
 [7,8,9]
];

Enter fullscreen mode Exit fullscreen mode

Accessing multi-dimensional arrays

A multi dimensional is an array that holds multiple arrays and since it is an array we can access it the same way.

Let's say we want to get the value 5, how do we do that. Keep in mind that an array uses zero-based indexing.

const numbers = [
 [10,11], //0
 [9,5], //1
 [7,8,9] //2
];

Enter fullscreen mode Exit fullscreen mode

So number 5 is found in the first index of the numbers array and is in the first index of that array.

Meaning you get the index of the array then the index of the item in that array
array[index of the array][index of item in the array]

const numbers = [
 //0 1
 [10,11], //0
 //0 1
 [9, 5], //1
 //0 1 2
 [7, 8, 9] //2
];

console.log(numbers[1][1]); //5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)