Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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
false

A 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
-1

So 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. 1

    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!.

  2. 2

    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.

  3. 3

    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.

Back

8/11

  1. 1. Introduction to Arrays
  2. 2. Creating Arrays
  3. 3. Accessing Array Elements
  4. 4. Changing Array Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: push()
  7. 7. Removing Elements: pop()
  8. 8. Searching an Array
  9. 9. Nested Arrays
  10. 10. Characters of a Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.