How correct is it to use || like ifnull in javascript?

I saw this code on the Internet:

function MyEventHandler(e) { var ev = e || event; var target = ev.srcElement || ev.target } 

In essence, the operator || used as an abbreviation for a?a:b . As far as I can tell, it works in all browsers. But, bringing up the specifications of, say, JScript, I see :

Performs a logical disjunction in two expressions.

and

JScript uses the following rules to convert non-Boolean values ​​to Boolean values:

  • All objects are considered true.

So ... according to this result there should be a boolean true / false. I'm just wondering: am I walking along a knife of undocumented behavior, or are there any subtle consequences here that I did not take?

+4
source share
3 answers

This behavior is well documented. See Chapter 11.11 ECMAScript Specifications: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

Unfortunately, this is not very easy to understand, but the last paragraph says:

The value generated by && or || an operator does not necessarily have a Boolean type. The resulting value will always be the value of one of the two operand expressions.

+4
source

No, I think you understand the coalescent behavior || .

EDIT:

&& also coalescent. does a && b behave like a ? b : a a ? b : a .

+4
source

This is simply an inaccuracy in the JScript specs. JScript is an implementation of the ECMAScript standard, so for a real state of affairs you should look at the ECMAScript specification.

+1
source

All Articles