Bruno Silva
Bruno Silva

Reputation: 119

Comparing a variable type number with an array using indexOf in Javascript

I have added a click event listener to a button. It calls the buttons YES AND NO. Basically the indexOf checks if the value in the variable foto is in the yesMeetup array or in the notMeetup array.

I tried to debug but I always get "You got it" and it's not calling the debugger when I click on NO button

let foto = Math.floor(Math.random() * 20) + 1;

document.querySelector('.btn').addEventListener('click', verify);

function verify() {
   var yesMeetup = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15];
   var notMeetup = [16, 17, 18, 19, 20];
   var notButton = document.getElementById('no');
   var yesButton = document.getElementById('yes');
   var decisao = document.getElementById('decisao');
   debugger;

   if (yesButton) {

        if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "You got it";
      } else if (notMeetup.indexOf(foto)) {
         decisao.textContent = "wrong";
      }

   } else if (notButton) {

      if (notMeetup.indexOf(foto)) {
         decisao.textContent = "You Gou it";
      } else if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "Wrong";
      }

   }
}

Upvotes: 5

Views: 266

Answers (2)

Mohit Kumar
Mohit Kumar

Reputation: 11

You can add click events to the buttons and check the values of the random variable. As the way you have written the code, it will always return the values for both the scenarios. Alternatively, to check the values at run time, you can use alert().

Upvotes: 0

nem035
nem035

Reputation: 35481

An if statement will evaluate anything passed into it as a boolean.

The only values for which it will not execute the "true" branch are all falsy values: 0, null, undefined, '', false, NaN.

Array.prototype.indexOf returns -1 when an element is not present in an array, which is not one of the falsy values and thus your if condition

if (array.indexOf(element))

will always evaluate as true.

var example = [1,2,3];
if (example.indexOf(4)) {
  console.log('still true');
}

You can use a direct comparison to -1:

var example = [1,2,3];
if (example.indexOf(4) !== -1) {
  console.log('this is not logged');
}

Or a newer, a bit cleaner, Array.prototype.includes:

var example = [1,2,3];
if (example.includes(4)) {
  console.log('this is not logged');
}

Upvotes: 4

Related Questions