views:

46

answers:

2

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?
+1  A: 

It's called "coalescing". It should behave the same in any browser that claims to be compliant.

Ignacio Vazquez-Abrams
+2  A: 

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).

Andy E