How to check if an array contains a specific value in JavaScript?
Hello everyone! I recently started learning JavaScript and came across this task: I have an array with city names, and I need to check if a specific city (e.g., "Moscow") is in it.
Here's my code:
```javascript
const cities = ["Moscow", "Saint Petersburg", "Kazan", "Novosibirsk"];
// I want to check if "Moscow" is in the array
if (cities == "Moscow") {
console.log("City found!");
}
```
But it doesn't work. I also tried:
```javascript
if (cities === "Moscow") {
console.log("City found!");
}
```
Still doesn't work. I understand that I'm comparing an array to a string, but how do I correctly check for the presence of an element? I've heard about the `includes()` method, but I'm not sure how to use it. I've also seen some people use `indexOf()`. Which approach is better? And wh
No answers yet.
Log in to leave an answer
Blogs