views:

101

answers:

5

I've come across two different ways to define/name objects and functions in JavaScript that first check for the existence of the name before using it. The issue is, I don't know which one is better (from speed and usability standpoints) and it's impossible to use the boolean operators in a Google search to figure it out.

The first one I see most often:

var myNewObject = myNewObject ? myNewObject : function () {
    // Code goes here.
};

The second one seems more concise, but I've only seen it one or two places, so I don't know if there's a standard or even a name for it:

var myNewObject = myNewObject || function() {
    // Code goes here.
};

Functionally, they both do the same thing and they both seem to work in every browser I can test in. My question is this - which is better and why? Also, while the first definition is essentially a single-line conditional ... what is the second one called?

+1  A: 

FWIW I see the second approach more often, and (for my part) I feel it's more clear, concise, and idiomatic.

Drew Wills
+5  A: 

I would use the second example, which is described as (Minimum Eval). Its simpler and seems more readable.

It's just like getting an event from onClick method across multiple browsers.

element.onclick = function (evt) {
  evt = evt || window.event
}
John Hartsock
+1 for the example
galambalazs
+2  A: 

I would choose the latter if only for the fact that you type myNewObject twice instead of thrice.

Also, while the first definition is essentially a single-line conditional ... what is the second one called?

Short-circuit evaluation

Matt
Accepting this as the answer since you also gave me the name of the second approach. It would have saved so much time had I know what it was called ... I didn't know it was a legitimate approach, just that it seemed to work.
EAMann
+2  A: 

The latter, it's similar to the null coalesce operator in c# ?? when used in that manner

see: http://stackoverflow.com/questions/476436/null-coalescing-operator-for-javascript

Chad
Note that is not completely equivalent, `??` in C# it will return the default value only when its left operand value is `null`, in JavaScript `||` will do it when its first operand is *falsy*, falsy values are: `null`, `undefined`, `0`, `NaN`, empty string, and `false`.
CMS
@CMS, yeah, hence the link for clarification. I should have wrote that it's *similar* to the `??` operator
Chad
A: 

Both methods work. But I think the most optimized version is to simply use a normal if test like:

if(!myNewObject)
   myNewObject = ...

Doing in any one of the method you suggest in your aanswer, it might involve an unnecessary reassigmnet everytime the fucntion/object is already defined. I mean if myNewObject is already defined, the Javascript runtime would have to perform an unnecssary reassigment myNewObject = myNewObject (unless the runtime doesn't optimize it out).

On Mozilla website they suggest to use a simple if, view this.

Marco Demajo