Unlock the Power of Array Searching with includes()

Finding a specific element in an array can be a challenging task. That’s where the includes() method comes in – a game-changer for efficient array searching.

The Syntax Breakdown

The includes() method takes two parameters: searchValue and fromIndex. The searchValue is the element you’re looking for, while fromIndex specifies the starting point for the search. By default, fromIndex is set to 0, but you can also use negative values to start the search from the end of the array.

const languages = ["C", "Python", "Java", "JavaScript"];
languages.includes("Java", -3); // returns true

Uncovering the Return Value

The includes() method returns a boolean value indicating whether the searchValue is found in the array. It returns:

  • true if the searchValue is found anywhere within the array
  • false if it’s not

Real-World Examples

Let’s put includes() to the test!

const languages = ["C", "Python", "Java", "JavaScript"];

console.log(languages.includes("C")); // returns true
console.log(languages.includes("Ruby")); // returns false

As expected, ‘C’ is found, but ‘Ruby’ is not.

Case-Sensitive Search

Be careful, though – the includes() method is case-sensitive. This means ‘Python’ and ‘python’ are treated as two different strings.

const languages = ["C", "Python", "Java", "JavaScript"];

console.log(languages.includes("Python")); // returns true
console.log(languages.includes("python")); // returns false

Using includes() with Two Parameters

What if we want to search for an element starting from a specific index? That’s where the second parameter comes in.

const languages = ["C", "Python", "Java", "JavaScript"];

console.log(languages.includes("Java", 2)); // returns false
console.log(languages.includes("Java", -3)); // returns true

With includes(), you can efficiently search for elements in your arrays and take your coding skills to the next level.

Leave a Reply