Searching an Array
Is a name on the guest list? Where in the queue is someone standing? Two methods answer questions like these.
The method includes() finds out whether an array contains a value. It returns true if it does and false if it doesn't:
const guests = ["Anna", "Tom", "Lucy"];
console.log(guests.includes("Tom"));
console.log(guests.includes("Paul"));This prints:
true
falseA boolean is exactly what a condition needs, so includes() is most often used with if:
const guests = ["Anna", "Tom", "Lucy"];
const visitor = "Tom";
if (guests.includes(visitor)) {
console.log("Come in!");
} else {
console.log("Sorry, you are not on the list.");
}This prints:
Come in!The method indexOf() tells you where a value is: it returns its index. If the value isn't in the array, it returns -1. Why -1? Because indexes start at 0, so -1 can never be a real index:
const queue = ["Anna", "Tom", "Lucy"];
console.log(queue.indexOf("Lucy"));
console.log(queue.indexOf("Paul"));This prints:
2
-1So the condition queue.indexOf("Paul") === -1 means “Paul isn't in the queue”. For a simple yes-or-no question, though, includes() reads better.
Both methods compare exactly, like ===. guests.includes("tom") returns false, because "tom" with a lowercase t isn't the same text as "Tom".
Instructions
- 1
Write an
ifstatement with the conditionguests.includes(visitor)that printsCome in!when the condition is true. Lucy is on the list, so the program printsCome in!. - 2
Add an
elsebranch that printsSorry, you are not on the list.Then change the value ofvisitorto"Paul"(in the lineconst visitor = "Lucy";). Paul isn't on the list, so now the program should printSorry, you are not on the list. - 3
Below the
ifstatement, print the index of"Max"withconsole.log(guests.indexOf("Max"));and then the index ofvisitorthe same way. The console should show3and-1.