JavaScript Array includes Method (Live Playground)
The includes method in JavaScript is a simple way to check if an array includes a certain value. This method returns true if the array contains the value, and false otherwise.
Let's take a look at a basic example:
let fruits = ['apple', 'banana', 'mango', 'orange'];
let includesBanana = fruits.includes('banana');
console.log(includesBanana);
// Expected output: true
In this code, fruits.includes("banana") checks if "banana" is in the fruits array. Since it is, the method returns true.
If we search for a fruit that isn't in the array, includes will return false:
let fruits = ['apple', 'banana', 'mango', 'orange'];
let includesGrapes = fruits.includes('grapes');
console.log(includesGrapes);
// Expected output: false
In this code, fruits.includes("grapes") is false because "grapes" is not in the fruits array.
You can also add a second argument to specify the index from where to start the search:
let fruits = ['apple', 'banana', 'mango', 'orange', 'banana'];
let includesBanana = fruits.includes('banana', 3);
console.log(includesBanana);
// Expected output: true
In this example, fruits.includes("banana", 3) begins its search from index 3. So it finds the "banana" at index 4 and returns true.
To sum up, the includes method is a handy way to check if an array contains a particular value. It's an essential tool when you need to determine the presence of a value in your array.
Don't forget to practice using includes with your own examples!