Alex Coleman
Alex Coleman

Reputation: 647

What is the use of a bitwise and, (&1), in javascript?

From the tutorial here,

function notePressed(event) {
  if (event.buttons & 1) {
    let dataset = event.target.dataset;

    if (!dataset["pressed"]) {
      let octave = +dataset["octave"];
      oscList[octave][dataset["note"]] = playTone(dataset["frequency"]);
      dataset["pressed"] = "yes";
    }
  }
}

What is the use of event.buttons & 1? Why is a bitwise AND being used?

Upvotes: 0

Views: 165

Answers (1)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

Here event.buttons returns an integer value, which represents that which mouse button is pressed. According to MDN it returns -

  • 0 : No button or un-initialized
  • 1 : Primary button (usually the left button)
  • 2 : Secondary button (usually the right button)
  • 4 : Auxiliary button (usually the mouse wheel button or middle button)
  • 8 : 4th button (typically the "Browser Back" button)
  • 16 : 5th button (typically the "Browser Forward" button)

So, ultimately what do we get from this event.buttons? An integer value.

Now come to your shared code snippet. What does the line if (event.buttons & 1) mean? Let's check some example of, what does the & 1 do with 32 bits integer.

0 & 1 => 0
1 & 1 => 1
2 & 1 => 0
3 & 1 => 1
23 & 1 => 1
46 & 1 => 0

So, if we perform & 1 with any 32 bits integer number then for Even numbers it returns 0 and for Odd numbers it returns 1. We can easily detect any odd/even numbers by using bitwise AND 1 operation.

Now you know 0 is a falsy value so the if condition never passes if we get 0 from the statement. So, if (event.buttons & 1) checks if the event.buttons gives an Odd number then execute the if block, otherwise not.

I hope I can clear it.

Upvotes: 2

Related Questions