Imagine you have a pile of papers from school, and you need to organize them. That's where arrays come in!
A data structure is a way of organizing data so that it can be used effectively. Arrays are one such data structure that helps us organize information.
In JavaScript, we can declare an array like this:
let numbers = [5, 10, 15, 20, 25];
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
let emptyArray = [];
- Array elements are listed inside square brackets and separated by commas.
An array element is each individual value in an array. For example:
let artists = ["Beyoncé", "Drake", "Billie Eilish", "BTS", "Ariana Grande"];
- Array name:
artists
- Array elements: ["Beyoncé", "Drake", "Billie Eilish", "BTS", "Ariana Grande"]
Arrays are frequently used in websites, apps, and games. Examples include photo galleries, music playlists, shopping carts, and more.
An array index is the location of an array element. The first array index is always 0.
You can retrieve a value from an array by using the array name followed by the index number in square brackets. For example:
let pets = ["guinea pig", "gecko", "bird", "cat", "snake"];
let favoritePet = pets[1];
console.log(favoritePet); // This prints "gecko"
Happy coding! 😊