AppDividend
Latest Code Tutorials

Javascript Array Includes Example | Array.prototype.includes() Tutorial

0

Javascript Array Includes Example | Array.prototype.includes() Tutorial is today’s topic. The includes() method determines whether the array contains the specified element. It returns true or false as output depending on the result. The Javascript Array includes() method is case sensitive.

Javascript Array Includes Example

The syntax of Javascript Array Includes is following.

array.includes(element, start)

The element parameter is required, and it is the element which we need to search.

The start parameter is an optional parameter, and the default is 0. It is the position in the array to start the search.

Let’s take an example of Javascript Array Includes.

// app.js

let arr = ['Gavin', 'Richard', 'Erlich', 'Gilfoyle'];

console.log(arr.includes('Erlich'));

As we know, Erlich is in the arr. So it will return true.

 

Javascript Array Includes Example

If we search for an element which does not exist in an array, then it will return the false.

// app.js

let arr = ['Gavin', 'Richard', 'Erlich', 'Gilfoyle'];

console.log(arr.includes('Jared'));

The output is following.

 

Array.prototype.includes() Tutorial

When comparing strings and characters, includes() function is case-sensitive.

The includes() uses the sameValueZero algorithm to determine whether the given element is found.

Let’s see other examples.

// app.js

console.log([1, 2, 3].includes(3, 2));
console.log([19, 21, 46].includes(19, 1));
console.log([19, 21, 46].includes(46, -1));
console.log([1, 2, NaN].includes(NaN));

The output of the above code is following.

 

Javascript Array Includes Example | Array.prototype.includes() Tutorial

If the start position is greater than or equal to the length of the array, then false is returned. The array will not be searched.

If the start position is negative, the computed index is calculated to be used as a position in an array at which to begin searching for the element. If the computed index is less or equal than -1 * array.length, an entire array will be searched.

Finally, Javascript Array Includes Example | Array.prototype.includes() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.