An array is a data structure that can be used to store a collection of items. Imagine if you had to store a list of your favorite soccer players, an array is the best data structure for that.
In JavaScript, there are several ways to define and initialize an array
It can be initialized like this
const playersArr = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
Or by using the Array constructor
// this creates an empty array with a length of 5
const arr1 = new Array(5);
// this creates an array with a length of 5 containing the number 7
const arr2 = new Array(5).fill(7);
Every item in an array is assigned an index. For playersArr
, "Ronaldo"
is at index 0, while "Dybala"
is at index 4. The index of any array starts at 0 and ends at the length of the array - 1.
const playersArr = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
// access items in the array
const ronaldo = playersArr[0];
const messi = playersArr[1];
const dybala = playersArr[4];
The items in a array can easily be modified by assigning a value to item's index
const playersArr = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
// modifiy an item
playersArr[1] = "Suarez"; // playersArr = ["Ronaldo", "Suarez", "Mbappe", "Neymar", "Dybala"]
The items in an array can be accessed sequentially using loops. A good use case for this is adding other names to each of our favorite players
const players = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
const otherNames = ["Cristiano", "Lionel", "Kylian", "Junior", "Paulo"];
const fullNames = [];
for (let i = 0; i < players.length; i++) {
fullNames[i] = `${otherNames[i]} ${players[i]}`;
}
In JavaScript, this can also be accomplished by using the map
method available on every array instance
const players = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
const otherNames = ["Cristiano", "Lionel", "Kylian", "Junior", "Paulo"];
const fullNames = players.map((player, i) => `${otherNames[i]} ${player}`);
In both cases, we get the result of
fullNames = [
"Cristiano Ronaldo",
"Lionel Messi",
"Kylian Mbappe",
"Junior Neymar",
"Paulo Dybala"
];
Arrays are very flexible in JavaScript and can be modified in several ways
const playersArr = ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"];
// NOTE: FOLLOW THESE OPERATIONS SEQUENTIALLY
// add an item to the end of the array
playersArr.push("Suarez"); // ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala", "Suarez"]
// add an item to the beginning of the array
playersArr.unshift("Suarez"); // ["Suarez", "Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala", "Suarez"]
// remove an item from the end of the array
playersArr.pop(); // ["Suarez", "Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"]
// remove an item from the beginning of the array
playersArr.shift(); // ["Ronaldo", "Messi", "Mbappe", "Neymar", "Dybala"]
// remove an item at a given index
playersArr.splice(1, 1); // ["Ronaldo", "Mbappe", "Neymar", "Dybala"]
Addition from the lesson that might be interesting: