Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why () are needed in this Javascript code block?

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>
like image 610
Huibin Zhang Avatar asked Sep 15 '26 15:09

Huibin Zhang


1 Answers

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.

like image 196
Arun P Johny Avatar answered Sep 17 '26 04:09

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!