简体   繁体   中英

Exponentiation operator for Boolean in JavaScript?

Refer to this , the exponentiation operator returns the result of raising first operand to the power second operand, like the exponentiation operator in Python, which is part of the ECMAScript 2016 (ES7) proposal.

We know the result of Boolean with exponentiation operator in Python as following:

>>> False ** False == True
True
>>> False ** True == False
True
>>> True ** False == True
True
>>> True ** True == True
True

I want to know whether the Boolean could be used in the exponentiation operator ? If so, could the same behavior as above in Python?

I'm not sure what kind of answer you expect. If you look at proposal you will notice that both operands are converted to numbers first. That means false ** false is equivalent to 0 ** 0 .

So yes, you can apply the operator to Booleans. Just like with all the other operators, the values are converted to the type that the operator expects.

The result will always be a number.

However, of course if you use loose comparison, then if the result of the exponentiation is 1 , it will loosely equal true , if it is 0 , it will loosely equal false .

Yes

console.log(false ** false == true);  // true
console.log(false ** true == false);  // true
console.log(true ** false == true);  // true
console.log(true ** true == true);  // true

If you use === all of those will be false though because 0 is not the same as false and 1 is not the same as true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM