Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How correct is it to use || as "ifnull" in JavaScript?

Tags:

javascript

I've seen code like this on the web:

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

In essence, the || operator is used as a shorthand for a?a:b. As far as I can tell - it works on all browsers. But bringing up specs for, say, JScript, I see:

Performs a logical disjunction on two expressions.

and

JScript uses the following rules for converting non-Boolean values to Boolean values:

  • All objects are considered true.

So... according to this the result should be a boolean true/false. I'm just wondering - am I walking the knife-edge of undocumented behavior, or is there some fine implication here that I haven't picked up?

like image 920
Vilx- Avatar asked Jan 20 '23 23:01

Vilx-


2 Answers

That behavior is quite well documenten. See Chapter 11.11 of the ECMAScript Specification: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

Unfortunately it's not very easy to understand, however the last paragraph states:

The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.

like image 88
RoToRa Avatar answered Jan 30 '23 18:01

RoToRa


No, I think you understand the coalescent behavior of || just fine.

EDIT:

&& is also coalescent. a && b behaves like a ? b : a.

like image 45
Ignacio Vazquez-Abrams Avatar answered Jan 30 '23 18:01

Ignacio Vazquez-Abrams