Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object definition conditionals - which is better?

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?

like image 577
EAMann Avatar asked Jul 09 '10 17:07

EAMann


3 Answers

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

like image 126
Matt Avatar answered Sep 30 '22 13:09

Matt


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
}
like image 44
John Hartsock Avatar answered Sep 30 '22 13:09

John Hartsock


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

see: Is there a "null coalescing" operator in JavaScript?

like image 36
CaffGeek Avatar answered Sep 30 '22 15:09

CaffGeek