Arrays
What you'll learn:
- read and replace an array element by its index and find out the array's length;
- add and remove elements at the start and at the end of an array;
- copy part of an array with
slice, cut elements out withspliceand find an element withindexOf; - explain why two variables can point to one array, and make a separate copy.
![A row of three lockers scores; a tile 2 goes into the middle one, scores[1], in place of the old tile](/course-covers/javascript-beginners/08-arrays.webp)
Picture the left-luggage lockers at a train station: a row of identical lockers, each with a number written on it. To pick up your bag, you don't open every locker in turn. It is enough to know the number and walk straight to the right one.
An array works the same way. As you already know from the for…of loop, an array is an ordered list of values, written in square brackets separated by commas. Each value is an element, and its number is an index. The numbers in this row of lockers start at 0, not at 1.
You can already go through the elements in order. But often you need one element: the third result, the last message, the first player. An array can do that too: it knows how many elements it holds, gives any element by its index and lets you replace it:
const scores = [5, 3, 4];
console.log(scores.length); // 3
console.log(scores[0], scores[2]); // 5 4
console.log(scores[3]); // undefined
console.log(scores[scores.length - 1]); // 4
scores[1] = 2;
console.log(scores.join(" ")); // 5 2 4Let's go through the program line by line:
scoresgets an array of three scores.scores.lengthprints3, the number of elements.scores[0]andscores[2]get the first and the third elements:5and4.scores[3]printsundefined: there is no locker number3.scores[scores.length - 1]gets the last element,4.scores[1] = 2puts2in place of the second element.scores.join(" ")prints5 2 4: the second score has been replaced.
Length and indexes
The length property holds the number of elements in the array. The empty array [] has the length 0. Indexes start at 0, so the last element is scores[scores.length - 1].
An index past the end of the array causes no error: the expression scores[3] gives undefined. A string behaves the same way when an index goes past its end.
One array can hold values of different types: [1, "one", true] is an array of three elements. Usually, though, the elements share one type, such as only numbers or only strings.
Replacing an element
Unlike a string, an array can be changed. The assignment scores[1] = 2 puts a new value in place of the second element, and the length stays the same. It is like putting a different bag into locker number 1: the row of lockers is still the same.
The array in the constant scores changes too. const forbids giving the name scores another array, but does not forbid changing the elements of the array itself.
This is where the locker analogy ends. A row of real lockers never grows or shrinks, while an array can become longer and shorter.
Printing and checking
Node.js prints an array whole, in square brackets. Let's see how else to turn an array into a string and how to check whether a value is an array:
const words = ["red", "green"];
console.log(words); // [ 'red', 'green' ]
console.log(words.join(" + ")); // red + green
console.log(words.join()); // red,green
console.log(typeof words); // object
console.log(Array.isArray(words), Array.isArray("red")); // true falseThe join method
To get one string out of an array, call the join method. It glues the elements together with the separator you pass, and with a comma when there is no argument. join does not change the array itself: it returns a new string, and numbers go into it as text.
typeof and Array.isArray
The typeof operator gives "object" for an array — the same answer as for null — so typeof cannot recognize an array. An array has no type name of its own: typeof cannot tell an array apart from other values of the type "object".
To check whether a value is an array, use the Array.isArray function: it returns true only for an array. For the string "red" it gives false, even though a string has indexes and a length too.
Common mistake
A loop over the indexes goes up to nums.length inclusive:
const nums = [2, 4, 6];
let total = 0;
for (let i = 0; i <= nums.length; i++) { // ✗
total += nums[i];
}There is no error, but total is NaN, not 12. On the last step, i is 3, and nums[3] is undefined. A sum with undefined gives NaN.
The last index is one less than the length, so the condition is written as i < nums.length. If you do not need the index, go through the elements with for…of.
Key points
- Array indexes start at
0, the last element isa[a.length - 1], and an index past the end givesundefined. - The assignment
a[i] = xchanges an element in place, even when the array is in a constant. joinglues the elements into a new string and does not change the array.typeofgives"object"for an array, and an array is checked withArray.isArray.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.