Codecademy will be down from 00:00 to 02:00 ET on November 15, 2019 for scheduled database maintenance. This will affect the website, learning environment, forums, and mobile app. We will provide updates as necessary.
Cheat Sheets are in BETA. Give us your feedback.

JavaScript Arrays

In JavaScript, arrays are lists of ordered, stored data. They can hold items that are of any data type. Arrays are created by using square brackets, with individual elements separated by commas.

// An array containing numbers const numberArray = [0, 1, 2, 3]; // An array containing different data types const mixedArray = [1, 'chicken', false, null];

Accessing JavaScript Array elements

JavaScript array elements are arranged by index values, starting at 0 as the first element index. Elements can be accessed by their index using the array name, and the index surrounded by square brackets. Array items can be changed by accessing the item and assigning it to a new value.

// Accessing an array element const myArray = [100, 200, 300]; myArray[1]; // 200 // Changing a value at an index let words = ['Hello', 'there']; words[0] = 'Hi'; console.log(words); // ['Hi', 'there']

JavaScript Array length property

The length property of a JavaScript array indicates the number of elements the array contains.

To obtain the length value, append the length property after the array name using a period.

const numbers = [1, 2, 3, 4]; numbers.length // 4

JavaScript Array .push() method

The .push() method of JavaScript arrays can be used to add one or more elements to the end of an array. .push() mutates the original array returns the new length of the array.

// Adding a single element const cart = ['apple', 'orange']; cart.push('pear'); console.log(cart); // ['apple', 'orange', 'pear'] // Multiple elements can be added by passing a comma-separated list const numbers = [1, 2]; numbers.push(3, 4, 5); console.log(nums); // [1, 2, 3, 4, 5]

JavaScript Array .pop() method

The JavaScript .pop() method removes the last element from an array and returns that element.

const ingredients = ['eggs', 'flour', 'chocolate']; const poppedIngredient = ingredients.pop(); // 'chocolate' console.log(ingredients); // ['eggs', 'flour']

JavaScript Arrays are mutable

JavaScript Arrays are mutable, meaning that the values they contain can be changed.

Even if they are declared using const, the contents can be manipulated by reassigning internal values or using methods like .push() and .pop().

const names = ['Alice', 'Bob']; names.push('Carl'); console.log(names) // ['Alice', 'Bob', 'Carl']