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?
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
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
}
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?
FWIW I see the second approach more often, and (for my part) I feel it's more clear, concise, and idiomatic.
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 answer, it might involve an unnecessary reassignment every time the function/object is already defined. I mean if myNewObject is already defined, the JavaScript runtime would have to perform an unnecessary reassignment myNewObject = myNewObject (unless the runtime doesn't optimize it out).
On Mozilla website they suggest to use a simple if, view this.
Related
On the MDN page for the wheel event, there is a code sample which includes the following at lines 30-31:
function( originalEvent ) {
!originalEvent && ( originalEvent = window.event );
The second line seems to take a number of shortcuts that rely on the way JavaScript evaluates boolean expressions internally. If I understand correctly, its purpose is to set originalEvent to window.event if no argument is passed. Its action is the same as the following:
if (!originalEvent) {
originalEvent = window.event;
}
or
orginalEvent = (originalEvent) ? orginalEvent : window.event;
What advantages are there in using the construction from the MDN site?
What advantages are there in using the construction from the MDN site?
Looking cool pretty much.
I was going to say terseness, but the following is just as short, and it's clear at a glance what's going on:
function(originalEvent) {
if(!originalEvent) originalEvent = window.event;
}
Do note however that their sample doesn't rely on any "internal" order of operations or anything sinister. Operator short-circuiting (which is what this is called) is a very well defined and popular part of many languages, of which Javascript is just an example. You could write the same exact statement in C and it would work fine.
There is no perfect advantage of MDN's way over the ways you suggested. It's a matter of style.
All of the ways you mentioned do the exact same thing.
MDN's way is a little more "concise", but other people prefer if...else statements like the one you noted for readability purposes. Depends on the specific circumstances, but I think in most cases, choosing between one or the other is a matter of style, and not necessarily optimization.
To add more obscurity you could also use
function(originalEvent) {
originalEvent = originalEvent || window.event;
}
There are no correct way of doing this, and they are all perfectly valid, I quite often use the one above, since i think it it more easily readable (though many will shake their fist at me for doing it).
I also believe that you could get all method to go through most JSLint'ers with their default setting, so it really is a matter of style.
I'm looking at Addy Osmani's gist for a publication/subscription pattern here:
https://github.com/addyosmani/pubsubz/blob/master/pubsubz.js
He surfaces his object as a global like this:
;(function ( window, doc, undef ) {
var topics = {},
subUid = -1,
pubsubz ={};
....
getPubSubz = function(){
return pubsubz;
};
window.pubsubz = getPubSubz();
What is the value of creating that getPubSubz function? Wouldn't it be more straightforward to simply write:
window.pubsubz = pubsubz;
Yes, in this case, because getPubSubz is only called in one place, immediately after declaring it, it could safely be inlined.
It's hard to say exactly what the author had in mind, but in a growing code base there may be some value to having a "getter" function which could be modified if the act of getting the pubsubz object required more advanced logic.
It absolutely would be.
There are only two potential reasons why a getter would be used in this case:
There was previously some additional code inside the getter (logging, perhaps)
Addy Osmani's just following good practice*, and including a getter—even adding the opportunity to add additonal code in the future.
Through the power of GitHub, we can actually eliminate option one, as the getter was added in its current state—so I think we can conclusively say that it's just a matter of good practice here.
*as jantimon alludes to in the comments below, this isn't particularly advantageous in most cases (including this one) and this code does not necessarily need to followed as an example.
I often find that I write IF statements which immediately reference the value of the conditional statement. For example, let's say I need to check to see if a string matches a pattern:
if (mystring.match(/mypattern/) {
var mymatch = mystring.match(/mypattern/)[1];
...
};
I suspect that what I'm looking for doesn't exist, but I've wondered whether you can reference the conditional statement's value within the if block, the way you can reference "arguments" within a function. In many cases, of course, I can rewrite it like this:
var mymatch = mystring.match(/mypattern/)[1];
if (mymatch) { ... };
But that's often not possible if there's a series of methods called. For example:
var mymatch = $('.myclass')[0].text().match(/mypattern/)[1];
... that would throw an exception if there were no item [0] on which to call .text(). Is there some convenient shorthand I'm missing out on? Or a better way to organize things? Just curious, really — I'll go on living if the answer is no.
In cases where relevant you can use the fact that the assignment operator returns a value in JavaScript, so for instance you can write things like:
if (assignedTest = testedValue) {
//value of assignedTest is now available
//and conditional will only be executed if true
This could be used if the RHS was compatible or properly set-up but it's also a huge readability concern since it's very easy to confuse the assignment = with comparison ==/===.
If you were particularly motivated to pursue this you could extract this type of functionality into a function that would behave in a reliable way: such as assigning the result of a closure to a named variable, and you could further tune the behavior to do other things (such as optionally evaluating to a different value within the test). Ultimately it would primarily be making a simple structure more complex though.
At emberjs documentation http://emberjs.com/documentation/#toc_computed-properties-getters, says that there are two ways to define computed properties. First is through prototype extensions and the second is by wrapping the function in a call to Ember.computed.
Can anyone tell me what is the deference between them and if one way is better than the other, cause in example code there is no obvious deference (or i am missing something?)
There is no difference between both variants - except that the Ember.computed approach is more verbose. In fact, the property variant internally invokes Ember.computed, see definition in function.js.
packages/ember-runtime/lib/ext/function.js:
Function.prototype.property = function() {
var ret = Ember.computed(this);
return ret.property.apply(ret, arguments);
};
I suppose there is none in the end. As stated, you can use the Ember.computed if you don't like your Function prototype extended. Might be useful for metaprogramming as well.
This question already has answers here:
Using 'return' instead of 'else' in JavaScript
(13 answers)
Closed 5 years ago.
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
Choose method 1 when you need to do more stuff in the block after the if-block.
Choose method 2 when you only need two blocks of code, it's then clearer to read
Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.
Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.
I would recommend method 1 as it is more readable and self documented.
Any modern browser's interpreter should eliminate any performance advantage in either direction.
There are a couple of reasons method 1 is preferable that haven't been mentioned yet. Having a single point of exit makes any future modifications that require an action common to both branches easier and less likely to be buggy (because the author missed the early return. Similarly, in some cases it makes debugging easier, by providing a common place to put a breakpoint or alert().
Readability here really depends on the role of the function.
If this function will ALWAYS return true, then I would prefer the Method 1 It is clear because it only returns in one place, and it is easy to see it will always be true.
In the above case, Method 2 is more confusing. It returns in multiple places, and is more confusing thusly. Consider a developer unnecessarily traversing possible branches and then seeing how they affect the return value. In this simple case, it is not as big of a deal, but when you get more elaborate conditionals, I would really avoid this approach.
I would only use Method 2 if you have very little code in the if block. Such as something that would deal with an edge case.
Hope that helps.