Introduction
For the convenience of programmers, nearly every programming language offers a variety of built-in methods. For example, JavaScript provides methods that significantly ease a developer's life. Today, we will explore JavaScript's includes() method. This article will cover the includes() method, from its definition to its functionality.
The includes() method is used to check if an array or string contains a specific value or element. It returns a true or false value based on whether the specified value or element is found.
Using the includes() Method
Using Includes() with Array
// Simple way to use this
[1, 2, 3].includes(3);
// output: true
['a', 'c', 'd'].includes('t');
// output: false
let array = ['apple', 'banana', 'mango'];
console.log(array.includes('apple'));
// output: true
The includes() method iterates over each element of the array and attempts to match it with the specified element provided within the parentheses (e.g., includes('3')). If a match is found, the method returns true; otherwise, it returns false.
It's important to note that the method may not work as expected in certain cases. For instance, if you're checking an array containing only the string abcdedfdeerewre as a single element, it will only return true if the exact element abcdedfdeerewre is present, not if you are searching for a character within that string.
console.log(['abcdedfdeerewre'].includes('a'));
// output: false
Using Includes() with String
The includes() method works similarly in both strings and arrays, but there are slight differences in behavior. In both cases, the method checks whether a specified element (or substring) is present, but the way it operates can feel different depending on whether you're dealing with a string or an array.
console.log('apple'.includes('a'));
// output: true
In the example above, includes('a') checks if the substring a is found within the string apple, and since it is, the output is true.
let string = 'apple';
console.log(string.includes('a'));
// output: true
Similarly, when using includes() on the string apple, it checks for the presence of the substring a, and the result is true.
let string = 'apple';
console.log(string.includes('pple'));
// output: true
Here, includes('pple') checks if the substring pple is found within apple, and since it is, the output is true as well.
In a string, it checks for the presence of a specified character or substring. For example, if we have the string apple, it contains five characters. If we use 'apple'.includes('a'), it will return true because the character a is present in the string apple. However, it will return false if we use 'apple'.includes('pel') because .includes() checks for the exact sequence of characters, and apple does not contain the substring pel. The method only returns true if the exact sequence of characters or the character itself exists in the string.