Click events with boolean

Why is it that Code 1 works and code 2 doesn’t? Do they not mean the same thing? Please explain


Code 1

let sorted = false;
btnSort.addEventListener('click', function (e) {
  e.preventDefault();
  displayMovements(currentAccount.movements, !sorted);
  sorted = !sorted;
});




Code 2

let sorted = false;
btnSort.addEventListener('click', function (e) {
  e.preventDefault();
  displayMovements(currentAccount.movements, true);
  sorted = false;
});

You are assigning true to sorted in the first code and false in the second.

It is also only the first time the code runs that hardcoding the values would work the same, as the next time the value is the opposite and would negate to false (and then to true, and so on).

let sorted = false;

sorted = !sorted;
console.log(sorted); // true

sorted = !sorted;
console.log(sorted); // false

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.