Simple array check

Hello!
I’m very new to JS, and I want to build a simple app that check words inside an array.
This is my code:

let input = 'a';
const words = ['a', 'b', 'a', 'd'];

for (let j = 0; j < words.length; j++){
  if (input === words[j]){
      console.log('found');
  }
else {
 console.log('err');}
}

I want to get “found”/“err” only one time, but this way inside a loop I get it 4 times.
I’m sure there is better way to write the code, thanks in advance for your help:)

The better solution would to use a function, so we can use return to break our loop once a match is found

if that is too much, we can simply use a variable to do this for us:

let input = 'a';
const words = ['a', 'b', 'a', 'd'];

// declare variable, for example found and set it to false
 if (input === words[j]){
      console.log('found');
     // set found to true
  }

then outside after the loop, check if found is false (not true).

1 Like

Nice, thanks a lot!:slight_smile: