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
Write an if statement with the condition guests.includes(visitor) that prints Come in! when the condition is true. Lucy is on the list, so the program prints Come in!.
Add an else branch that prints Sorry, you are not on the list. Then change the value of visitor to "Paul" (in the line const visitor = "Lucy";). Paul isn't on the list, so now the program should print Sorry, you are not on the list.
Below the if statement, print the index of "Max" with console.log(guests.indexOf("Max")); and then the index of visitor the same way. The console should show 3 and -1.
Start programming for free
8/11