JavaScript Glossary: Array .includes() Method
Publikováno: 8.2.2019
Basics
This method checks if an array contains a given element. The return value for this method is a Boolean
. true
if the element exists in the array and f...
Basics
This method checks if an array contains a given element. The return value for this method is a Boolean
. true
if the element exists in the array and false
if otherwise.
[10, 20, 30, 40].includes(50)
// False
https://scotch.io/embed/gist/c159aaeb3d1a370beb49762afa955232
Array.includes()
:
- Takes a value as an argument
- Checks the array if the value exists within the array
- Returns
true
orfalse
. - If no argument is provided, it returns
false
.
Syntax
array.includes(searchValue, startIndex)
2 Parameters
searchValue This is the value to search the array for.
startIndex (optional) This the position in the array at which the search begins.
Returns a boolean
The method will return an the Boolean true
if the array contains the searchValue
and false
if it doesn’t. If no arguments are provided, false
is returned by the method.
const names = ['Johnny', 'Pete', 'Sammy']
const myName = 'Pete';
const hasMyName = names.includes(myName);
console.log(hasMyName);
// output: true
Common Uses and Snippets
Checking if an array contains a certain value
The includes
method is commonly used to check if an array has a certain value in it.
https://scotch.io/embed/gist/518cc1b412d7cbf931fa5f1d2f81e3a1