JavaScript Program to Check if An Array Contains a Specified Value
Learn JavaScript Program to Check if An Array Contains a Specified Value step by step with clear examples and exercises.
Why This Matters
In programming, working with arrays and checking for specific values is a common task that arises in numerous real-world scenarios such as filtering data, validating user input, and debugging code. Mastering this skill will enable you to write more efficient and effective JavaScript programs. In this lesson, we will learn how to use the includes() method in JavaScript to determine if an array contains a specified value.
Prerequisites
Before diving into the core concept, it is essential to have a basic understanding of:
- Variables and data types in JavaScript
- Arrays in JavaScript
- Basic syntax and operators in JavaScript
- Control structures like loops and conditional statements
Core Concept
The includes() method is used to check if an array contains a specified value. It returns a boolean value (true or false) based on the search result. Here's the basic syntax:
array.includes(searchValue);
Let's break down this code:
arrayis the name of the array we want to check.searchValueis the value we are looking for in the array.- The method returns
trueif the array contains the specified value andfalseotherwise.
Example 1: Check Array Using includes()
Let's create an example to better understand this concept:
const array = ['apple', 'banana', 'cherry'];
const hasValue = array.includes('apple'); // check the condition
console.log(hasValue); // Output: true
In the above program, we have an array containing fruits. We use the includes() method to check if this array contains the value 'apple'. Since it does, the output is true.
Example 2: Checking for Multiple Values
You can also use the includes() method to search for multiple values in an array by passing them as elements of another array or by concatenating them with commas:
const fruits = ['apple', 'banana', 'cherry'];
const hasFruits = fruits.includes(['apple', 'orange']); // check for multiple values
console.log(hasFruits); // Output: true if the array contains at least one of the specified values, false otherwise
Example 3: Using includes() with Custom Objects
By default, includes() checks for strict equality (===), so it will not find custom objects unless they have the exact same properties and values as the search value. To make it work with custom objects, you may need to override the toString() method or implement a custom comparison function:
function Person(name, age) {
this.name = name;
this.age = age;
}
const people = [new Person('Alice', 30), new Person('Bob', 25)];
const hasPerson = people.includes(new Person('Alice', 30)); // check for a custom object
console.log(hasPerson); // Output: true or false depending on the presence of the specified object in the array
In this example, we create a Person constructor and use it to create objects with names and ages. We then check if our array contains a specific person using the includes() method. However, since the method checks for strict equality by default, it will not find the object unless we override the toString() method or implement a custom comparison function.
Common Mistakes
- ### Forgetting to check for the presence of the value
It's essential to assign the result of the includes() method to a variable and check its value instead of directly comparing the array with the search value:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers === 7); // Output: false (comparing arrays and numbers is not equal)
Instead, use the includes() method to check for the presence of a value:
const numbers = [1, 2, 3, 4, 5];
const hasSeven = numbers.includes(7);
console.log(hasSeven); // Output: false or true depending on the presence of 7 in the array
- ### Using
indexOf()instead ofincludes()
While both methods are used to search for a value, they have different behaviors:
indexOf()returns the index of the first occurrence of the specified value or -1 if not found.includes()checks for the presence of the specified value and returns true or false.
Using indexOf() when you need to check for the presence of a value can lead to confusion:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.indexOf(7) !== -1); // Output: true or false depending on the presence of 7 in the array
Instead, use includes() to check for the presence of a value more straightforwardly:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(7)); // Output: true or false depending on the presence of 7 in the array
Worked Example
Let's create a more complex example that demonstrates how to use the includes() method in practice:
const numbers = [1, 2, 3, 4, 5];
let foundNumber;
// Loop through the array and check if it contains the number 7 or 9
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 7 || numbers[i] === 9) {
foundNumber = true;
break;
} else {
foundNumber = false;
}
}
console.log(foundNumber); // Output: true or false depending on the presence of 7 or 9 in the array
In this example, we have an array of numbers. We loop through each element and check if the number 7 or 9 is present. If found, we set foundNumber to true, otherwise, it remains false. Finally, we log the value of foundNumber to confirm whether the number 7 or 9 is in the array or not.
Practice Questions
- Write a JavaScript program to check if an array contains the value 'orange'.
- Modify the worked example to find multiple values (e.g., 7, 9, and 11) in the numbers array.
- Create a function that takes an array and a search value as arguments, and returns true if the array contains the specified value; otherwise, return false.
- Write a JavaScript program to check if an array contains any odd numbers.
- Write a JavaScript program to find all the vowels in a string using the
includes()method (Hint: Convert the string to an array of characters first). - Write a JavaScript program to check if an array contains duplicate values.
- Write a JavaScript program to remove all occurrences of a specified value from an array using the
includes()method and splice(). - Write a JavaScript program to find the index of the first occurrence of a specified value in an array using the
indexOf()method, and then use that information to remove all subsequent occurrences of that value using the splice() method. - Write a JavaScript program to sort an array of objects based on a specific property using the
sort()method. - Write a JavaScript program to find the maximum and minimum values in an array using the
Math.max()andMath.min()methods.
FAQ
### Can I use includes() with negative indexing?
No, the includes() method does not support negative indexing. Use indexOf() for that purpose instead.
### What happens if the search value is an empty string when using includes()?
The includes() method returns true if the array contains an empty string ("") or if the array is empty itself.
### Can I use includes() with custom objects in JavaScript?
Yes, but it depends on how you define equality for your custom objects. By default, includes() checks for strict equality (===), so it will not find custom objects unless they have the exact same properties and values as the search value. To make it work with custom objects, you may need to override the toString() method or implement a custom comparison function.
### What is the time complexity of the includes() method in JavaScript?
The time complexity of the includes() method in JavaScript is O(n), where n is the length of the array being searched. This means that the performance of the method degrades linearly as the size of the array increases.