Press ESC to close

JavaScript array includes

0 1610

JavaScript array includes method allows you to check if an element is present in an array or even in a text string, as explained in this lesson: https://www.codingcreativo.it/en/javascript-includes/.

The syntax of this method is as follows:

array.includes(element)

Where element is the element to search for in the array.

Optionally, you can also indicate the position from which to start the search by adding a second parameter as an argument to the includes method of js.

array.includes(element, start).

The includes method returns a boolean value:

  • true if the element is present in the array,
  • false if the element was not found.

JavaScript array includes – first example

Search an element in an array with the includes () method.

So let’s suppose we have the following array:



var schoolObject = ['eraser', 'notebook', 'pencil'];

Then, we apply the include method to get the boolean return value stored in a variable.



var result = schoolObject.includes('eraser');

In this case, if we try to make the result console.log we will have the boolean value true in return.

If, on the other hand, we are looking for a value that is not present:



var result = schoolObject.includes('Sharpener');

The value of the result variable will be false.

JavaScript array includes – second example

Create an array of integers of your choice. After generating a random number between 1 and 100. If the number is not present in the array we insert it, otherwise we return the message “number already present”.

So first let’s create an array of integers of your choice. Next we generate a random number using the Math.floor and Math.random functions.

After using a simple conditional statement with the logical operator not we check if the number is not present and in this way we insert it into our array. Otherwise we display the message with a simple alert.

So here is the example code that uses the includes method of js:



var arrayNumbers = [6,12,34,67,89,98,5,2,7,13];
var numberRandom = Math.floor(Math.random() * 100) + 1;

if (!arrayNumbers.includes(numberRandom)){
  arrayNumbers.push(numberRandom);
} else {
  alert('Number is present');
}

Conclusion

In this lesson we have simply seen examples of using the JavaScript array includes, in the next lessons I will propose many other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

Math random

Next Story

JavaScript includes

Previous Story