JavaScript Arrays and Array Methods
Overview
An array is a data structure that contains a list of elements which store multiple values in a single variable. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Prepare
In JavaScript, arrays can be declared like this:
let scores = [100, 72, 83, 94, 88, 87];
let names = ['Nancy','Blessing','Jorge','Svetlana'];
Arrays are zero-based indexed, meaning the first element is at index 0, the second element is at index 1, and so on.
Arrays can be accessed by an index reference:
let aScore = scores[0]; // The aScore variable is assigned the value of 100
Arrays values can be modified:
scores[0] = 99; // This assignment expression changed the first score in the array from 100 to 99.
Arrays can be iterated over using a classic for loop:
for (let i = 0; i < scores.length; i++) {
console.log(scores[i]);
}
Arrays can be iterated over using other looping structures like forEach
:
scores.forEach(function(score) {
console.log(score);
});
Arrays have a length
property:
let numScores = scores.length; // The numScores variable is assigned the value of 6
Array Methods
Arrays have a number of methods that can be used to manipulate (change) them:
scores.push(100); // Adds a new element to the end of the array
scores.pop(); // Removes the last element from the array
scores.shift(); // Removes the first element from the array
scores.unshift(100); // Adds a new element to the beginning of the array
scores.splice(2, 1); // Removes 1 element from the array starting at index 2
- Reference 📑JavaScript Arrays Reference - MDN web docs
This reference provides a complete list of array methods of which some will be used extensively in this course.
Check Your Understanding
Given this array declaration:
let names = ['Nancy','Blessing','Jorge','Svetlana'];
- What is the value of the following expression?
names[2];
Answer
Jorge
- What is the value of the following expression?
names.length;
Answer
4
- What is the index of the last item in the array? (Svetlana)
Answer
3
- What does the following expression do?
names.push('Sally');
Answer
Adds a new element to the end of the array