An array is an object used to store a collection. This collection could be anything: numbers, objects, more arrays, etc. In JavaScript, arrays are used to store multiple values in one variable that can be accessed through an index (which starts from zero). The values stored in the array are called elements and the number of elements stored in an array is typically referred to as the array’s length. For example, in the illustration given below, the length of the array is five
:
In JavaScript, there are two ways to declare an array:
This is the most basic way to declare and initialize an array in JavaScript:
var my_array = [1,3,5,2,4]console.log(my_array)
You can also declare an array using a JavaScript built-in Array class and initialize it by passing the values inside the brackets, like this:
var my_array = new Array(1,3,5,2,4)console.log(my_array)
To access a particular element in an array, you will need to know the index of that element.
For example, if you want to access the fourth element, “2”, you would write:
var my_array = [1,3,5,2,4]var my_element = my_array[3]console.log(my_element)
The syntax to modify a value at a particular index, let’s say 2
, is this:
var my_array = [1,3,5,2,4]console.log(my_array[2])my_array[2] = 0console.log(my_array[2])
Yes, you read that right. Arrays in JavaScript are objects. If you look at the typeof
of an array, it will return an object
.
var my_array = [1,2,3,4,5]console.log(typeof my_array)
Free Resources