ECMAScript 2016 – Finding if a value exists in an array using JavaScript

We gonna use ECMAScript 2016’s new includes() method to determine whether an array contains a specific element. The new method includes(searchElement, fromIndex) function searches an array for a specific value and returns the corresponding boolean, return true if it exists otherwise false. An optional argument fromIndex allows to search from a specific index.

Let’s see some basic examples:

Syntax of includes()

Parameters
searchElement – The element to search for.
fromIndex(Optional) – Default value is zero. The position in this array at which to begin searching for searchElement. A negative value searches from the index of array.length + fromIndex by asc.

Let’s see concise examples:

'PHP' element has index 0 in technologies. However the search starts from 1 and the index 0 is skipped, so the element is not found.

'JS' has index 1, thus the search starts from index 1 , so include() is able to find it.

The 'Ruby' element is checked from index 10, which is bigger than the array length 4. includes() method for such situations returns false.

The index to begin searching parameter is a negative number -3 and the search starts from index 4 - 3 = 1. The searched 'PHP' is compared only with 'JS', 'Ruby' and 'NodeJS' elements, so there is no match.

When searching for 'NodeJS' element with the same -3 offset, it is a matches.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.