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.
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.
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.
& 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)
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 why0001 & 0001 = 0001 => 1