Arrays
An array in Javascript is a collection of items that are all stored in a single variable, very similar to a list. Arrays can hold any type of data, including strings numbers, or even other arrays. An array is defined using square brackets []
, with a comma in between each value in the array.
const fruits =["apple", "banana", "orange"]
To access values inside of an array, you can use their index, or their position in the array. In JavaScript (and nearly all programming languages), indexing for arrays starts at 0. You can see how this works in the example below:
console.log(fruits[0]) // Outputs: "apple"
console.log(fruits[1]) // Outputs: "banana"
console.log(fruits[2]) // Outputs: "orange"
Arrays, like other variables, can also be edited. You can change the element at any array just like how you would update a regular variable, or you can add to and delete elements from the end of the array with the push()
and pop()
functions
fruits[1] = "blueberry" // Replace "banana" with "blueberry"
console.log(fruits) // Outputs: ["apple", "blueberry", "orange"]
fruits.push("pear") // Adds "pear" to the end of the array
console.log(fruits) // Outputs: ["apple", "blueberry", "orange", "pear"]
fruits.pop() // Removes the last element ("pear")
console.log(fruits) // Outputs: ["apple", "blueberry", "orange"]
Arrays are incredibly useful in JavaScript as they allow us to store collections of data efficiently, rather than having to store every piece of data in its own variable. They’re particularly useful when used with loops, which are covered in the following section.