'Very large string arrays not working as expected

I have an array with 58112 words. However, when I try to check if a word is in the list, it always returns false, except for the first word. I'm not going to post my code because that would be too large, but here is some of the main stuff:

isWord("a") //true
isWord("hello") //false??

function isWord(word) {
  word = word.toLowerCase();
  for (let i = 0; i < words.length; i++) {
    if (word == words[i]) {
      return true;
    } else {
      return false;
    }
  }
}

words[] is the list of 58112 words. The first word is "a", of course. When I do isWord("a"), it returns true, like expected. If I do anything other than "a", It returns false. Why does this occur? Is it because I exceeded the maximum array limit? I don't think so.
The words I used are from this (I had to add the "a" and the "i" because they didn't have one).



Solution 1:[1]

Here is a faster and more concise way to achieve the same functionality.

function isWord(word) {
    word = word.toLowerCase()
    var i = word.length;
    while (i--) {
       if (words[i] === word) {
           return true;
       }
    }
    return false;
}

Solution 2:[2]

Since ES7 (ES2016), two appropriate methods has been added:

const words = ['hi', 'bye', 'morning', 'evening'];
const toSearch = 'Morning';

if (words.includes(toSearch.toLowerCase())) {
  // ...
}
// or
if (words.some(x => x === toSearch.toLowerCase())) {
  // ...
}

While array's items are comparable by ===, using includes method is a better choice. Keep in mind, if === doesn't satisfy, use some method to customize it.

Use case of some method, where includes doesn't work:

const objects = [{ id: 1, name: 'Foo' }, { id: 2, name: 'bar' }, { id: 3, name: 'Baz' }];
const idToSearch = 2;

if (objects.some(x => x.id === idToSearch)) {
  // ...
}

Also, find and findIndex methods are there already, since ES6 (ES2015)

Solution 3:[3]

I may be wrong, but I think this is because when you are checking whether the word is in the words array or not.

In the first iteration of the array if it finds that the word that you entered is a which is the value of words[0], it returns true. Otherwise, if it it returns false and exits out of the function.

So essentially it only checks whether the element you entered is equal to a or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kush
Solution 2 Mr. R
Solution 3 Yaakov Ellis