0

Can someone explain to me why in this 'for ... of' loop '&&' achieves what I want but '||' doesnt? I'm making a simple calculator and I don't want the 'AC' and '=' buttons to add to my equation so I'm trying to attach a handleInput() function to all others buttons but not to 'ac' and '=' buttons.

//Target all elements with the 'btn' class.
const btnsDOM = document.querySelectorAll('.btn');

//Attach an event listener to every button expect for 'ac' or 'equals'
for (let i of btnsDOM) {
  if (i.dataset.btn !== 'ac' || i.dataset.btn !== 'equals') {
    i.addEventListener('click', handleInput);
  }
}

The above code will work as intended on the 'ac' button and not attach the event listener but the button with 'equals' in the dataset will still have the event listener attached.

The below code works. Only difference is the use of && instead of || in the if statement :

//Target all elements with the 'btn' class.
const btnsDOM = document.querySelectorAll('.btn');

//Attach an event listener to every button expect for 'ac' or 'equals'
for (let i of btnsDOM) {
  if (i.dataset.btn !== 'ac' && i.dataset.btn !== 'equals') {
    i.addEventListener('click', handleInput);
  }
}

This leaves be confused as I'd expect that with the '&&' operator, only a single button element with BOTH 'ac' and 'equals' dataset would be omitted from having the event handler attached.

  • If the value is `"ac"` then it's *not* `"equals"`, so `false || true` is `true`. The opposite also applies `true || false` is `true` – VLAZ Mar 24 '21 at 07:15
  • If dataset is 'ac' of course it won’t be 'equals', and same the other way around, so your condition always évaluâtes to true – Oskar Zanota Mar 24 '21 at 07:36

0 Answers0