Arrays
Use this article as a reference sheet for JavaScript arrays.
- Arrays — lists of numbers, strings, booleans, or any other data type.
- Array access — each item in the array can be accessed by its numeric index.
JavaScript arrays are zero-indexed. This means that the first item in an array is at position 0.
var products = ['soccer ball', 'cleats', 'socks', 'shorts'];console.log(products[0]); // 'soccer ball'console.log(products[3]); // 'shorts'
In the example above, the variable products
is an array of four strings. The array is created using bracket ([]
) notation. Each array item is separated by a comma. On line 2, the first array item ('soccer ball'
) is accessed using its position in the array (0
) and logged to the console. On line 3, the last item ('shorts'
) is accessed using its position in the array (3
) and logged to the console.
An array can contain items of differing data types. For example, you can create an array that stores both numbers and strings. You can even nest an array inside of another array to create a two-dimensional array.
var twoDimensional = [[41, 13], [7, 29]];
The array in this example is two-dimensional because it contains two nested arrays. Each nested array contains two numbers. In order to access items inside of the nested arrays, you must first access one of the nested arrays by index. Then, you can access an item inside of that array by its index.
console.log(twoDimensional[0]); // access first arrayconsole.log(twoDimensional[0][1]); // access 13 in first array
In the example above, the first line logs the array [41, 13]
to the console. The second line logs 13
to the console. The code, twoDimensional[0]
, accesses the first element in the array, which is the array [41, 13]
. The code on line 2, twoDimensional[0][1]
, accesses the first element ([41, 13]
) and then accesses the second element in this nested array, 13
.
The output of this code is:
[41, 13]13
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Javascript Guide: Arrays
Use this guide to brush up on interacting with JavaScript arrays. - Article
Creating and Using NumPy Arrays - A Complete Guide
In this article, we will discuss how to create and use NumPy arrays. We will also go through various array operations, indexing, slicing, and reshaping with practical Python examples for data science.