JavaScript object definition conditions - which is better?

I found two different ways to define / name objects and functions in JavaScript that first check for a name before using it. The problem is that I don’t know which one is better (in terms of speed and usability), and it’s impossible to use logical operators in a Google search to figure this out.

The first one I see most often:

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

The second one looks shorter, but I saw only one or two places, so I don’t know if there is a standard there or even a name for it:

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

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

+7
javascript object
source share
5 answers

I would choose the latter, if only so that you would myNewObject twice, not thrice.

Furthermore, although the first definition is essentially a one-line conditional ... what is called the second?

Short circuit rating

+5
source share

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

This is similar to getting an event from the onClick method for multiple browsers.

 element.onclick = function (evt) { evt = evt || window.event } 
+5
source share

Last, it is similar to the operator of zero coalescence in C # ?? when used in this way

see below: Is there a “null coalescing” operator in JavaScript?

+2
source share

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

+1
source share

Both methods work. But I think the most optimized version is just to use a regular test, for example:

 if(!myNewObject) myNewObject = ... 

By performing any of the methods that you suggest in your answer, this may require unnecessary reassignment every time a function / object is already defined. I mean, if myNewObject is already defined, the JavaScript runtime will have to unnecessarily reassign myNewObject = myNewObject (unless the runtime optimizes it).

The Mozilla website suggests using simple if you look at it .

0
source share

All Articles