Skip to content

Try our new Crash Courses!

Become a member using the button below to hide this banner and gain access to our new Crash Courses.

Arrays – JavaScript

Summary

In JavaScript, arrays are written using square brackets:

const myArray = [12, true, 'A string'];

Details

In JavaScript, you can store a list of values in what’s called an array. Arrays are wrapped in square brackets and the values are separated by commas.

An array can contain only one type of data, or you can mix different data types inside an array, like this:

const sameArray = ['a', 'b', 'c'];
const mixedArray = [12, true, 'A string'];

To access an item inside an array, write the name of the array, then a pair of square brackets. Inside the square brackets, you put a number that corresponds with the item you want, like this:

arrayName[0] // Access the 1st item in an array

Arrays in JavaScript are zero-indexed, which means to access the first element you use the number zero as the index. To access the second element, you would use the number one for the index, and the pattern continues from there.

arrayName[1] // Access the 2nd item in an array
arrayName[2] // Access the 3rd item in an array

Here’s an example of printing out the first item in an array to the console:

console.log(myArray[0]);

If you want to change a particular value in an array, you can use an equals sign, just like with any other variable. Here’s an example:

// Assign new value to array item
myArray[0] = 'New value';

Demo

Exercises

Try the following statements in the console:

const myArray = [12, true, "A string"]
myArray[0]
myArray[1]
myArray[2]
myArray[0] = "New value"

References

Array literals on MDN

Back to: JavaScript Reference > JS Data Types