-1
console.log(true & true);

I am a novice developer who is learning JavaScript. I wonder why 1 is printed out if I write the code above.

  • If you want to "true" result. Try && instead of &. Javascript operators are little bit strange :) – cbalakus Mar 16 '21 at 07:39
  • I am too curious about this. Best I can find is this docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND – krisanalfa Mar 16 '21 at 07:41
  • @cbalakus Actually, almost every C-like languages use these operators the same way as JS does... – FZs Mar 16 '21 at 07:42
  • [Is there a & logical operator in Javascript](https://stackoverflow.com/q/3374811) – VLAZ Mar 16 '21 at 08:13

3 Answers3

3

In JavaScript, true is evaluated to 1.

So, in short:

console.log(true & true)

is equal to:

console.log(1 & 1)

The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. It's boolean logic.

Read more about boolean logic here.

Nicholas D
  • 1,729
  • 1
  • 4
  • 16
0

& is a bit operator and work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. Any non-numeric operand is similarly converted to a number before the operation. The result is converted back to a JavaScript number.

&& is a logical operator and will return true or false

console.log(true & true);
console.log(true && true)
VLAZ
  • 18,437
  • 8
  • 35
  • 54
angel.bonev
  • 1,477
  • 1
  • 13
  • 21
0

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. In your case:

true = 1 => 0001 Thats why 0001 & 0001 = 0001 => 1

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

ref: https://www.w3schools.com/jsref/jsref_operators.asp

Jakir Hossen
  • 382
  • 3
  • 10