JavaScript

How to check if an element exists in array with JavaScript

October 28, 2021

How to check if an element exists in array with JavaScript

In this article we will learn in a practical way how to check if an element exists in array, applying a method that already exists in the JavaScript language!

verify if an element exists in array cover

What’s up, programmer, okay? What about learning something new!

Watch this content on YouTube:

So guys, a problem many programmers face is: check if such an element is in the array

And to our delight JavaScript has a ready-made method for that

Let’s say we have an array of names and our mission is to find a specific name

Let’s see this hypothesis in practice:

let nomes = ['Matheus', 'Henrique', 'João', 'Pedro'];

if(nomes.includes('Matheus')) {
 console.log("We found Matheus!");
}

With the includes method, we will receive a true or false return

If it finds the result, the method returns true

So we can assign this to an “if” for example and proceed to some different logic if the result is found

Cool huh? 

And if you need to check the element’s index in the array, you should use the indexOf method, check it out:

let numeros = [0, 1, 2, 1, 0];

console.log(numeros.indexOf(1)); // 1

You can include the element check in a variable, to use in the future on your software

The result is a boolean, if element is in array you receive a true, and if its not a false

These are the only two values you can receive from the boolean type of data

Conclusion

In this article we learned how to check if an element exists in array

Using the includes method, we get a “true” return if the element is found and if not a “false” return

And that’s it for today; see you on the next post! 

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x