Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - Boolean operators which return one of the operands

In Python, and maybe in Javascript, the boolean or and and operators return one of the operands, instead of true or false.

  • In Python, one of the operands is returned: '' || 'hello' == 'hello'
  • In comparison, in PHP: '' || 'hello' == true;

Now,

  • How is this behavior of boolean operators called?
  • Does this also work in Javascript in all browsers?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Ignacio's answer points out, these are coalescing operators. || is the null coalescing operator, && is the null-safe coalescing operator (link to follow, if I can find one sorry, I can't find a link).

They should be available in all browsers - they are both defined in the ECMA-262 1st, 2nd, 3rd and 5th editions, most current Javascript implementations are based upon 3rd or 5th. From ECMA-262 3rd edition:

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
1. Evaluate LogicalANDExpression.
2. Call GetValue(Result(1)).
3. Call ToBoolean(Result(2)).
4. If Result(3) is false, return Result(2).
5. Evaluate BitwiseORExpression.
6. Call GetValue(Result(5)).
7. Return Result(6).

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:
1. Evaluate LogicalORExpression.
2. Call GetValue(Result(1)).
3. Call ToBoolean(Result(2)).
4. If Result(3) is true, return Result(2).
5. Evaluate LogicalANDExpression.
6. Call GetValue(Result(5)).
7. Return Result(6).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...