Length and the Last Element
Often you don't know how many elements an array has. Maybe another part of the program filled it, or the number of elements changes while the program runs (you'll learn to add and remove elements in the next exercises). You can always find out with .length:
const students = ["Jennifer", "Boris", "Nancy", "David", "Ava"];
console.log(students.length);This prints:
5The dot connects a value with something that belongs to it. students.length means “the length of students”, that is, the number of its elements. A value that belongs to another value like this is called a property. The length property is a number, so you can store it in a variable or calculate with it.
With .length, you can get the last element of any array. Indexes start at 0, so the last index is always one less than the number of elements: an array of 5 elements has indexes 0, 1, 2, 3 and 4. The last element is therefore at index students.length - 1:
const lastStudent = students[students.length - 1];
console.log(lastStudent);This prints:
AvaJavaScript first calculates the index in the square brackets (5 − 1 = 4) and then reads the element at that index. Compared with students[4], this has one big advantage: it works for an array of any length, even when you don't know the length in advance. A common mistake is to forget the - 1: students[students.length] asks for index 5, where there is no element, and gives undefined.
Instructions
Print the number of coworkers: console.log(coworkers.length);
Create a constant lastCoworker and store the last element of coworkers in it. For the index, use coworkers.length - 1, not the number 2.
Print lastCoworker.