I understand there are many pitfall in javascript, but I still don't understand there are any difference between expression a&1 and (a&1) ??
the following code tries covert 11 (10 base) to a string 1101 (2 base)
<script>
var str = '';
var a = 11;
for(var i=0;a;i++){
str = a & 1 + str; // this doesn't work must rewrite as
// str = (a & 1) + str;
console.log('str = ' + str);
a >>>=1;
}
console.log(str);
</script>
It is because of operator precedence
The Addition has a higher precedence than Bitwise AND. So when a & 1 + str is evaluated the 1 + str is evaluated first then a & result is evaluated.
Using Grouping Operator we can change the evaluation order. So when (a & 1) + str is evaluated, contents inside () (a & 1) is evaluated first result + str is evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With