if..else vs if(){return} [duplicate] - javascript

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.

Related

Which is more efficient in a function: conditional execution or conditional exit?

I would really hear some opinions on which of the following solutions is more efficient in JavaScript/TypeScript:
function whatever(param) {
if (param === x) {
doStuff();
}
}
or
function whatever(param) {
if (param !== x) { return false; }
doStuff();
}
Obviously the second one reduces the number of blocks and improves code readability, but does it offer any benefits or drawbacks compared to the first one?
In assembly you'd write both as:
// first
whatever:
CP x, param
JP nz, whatever2
CALL doStuff
whatever2:
RET
// second:
whatever:
CP x, param
JP z, whatever2
RET
whatever2:
CALL doStuff
RET
So while the first one uses 4 instructions, the second uses 5. So in case the JS engine is able to optimize it down to this optimal bytecode (very unlikely, but it makes estimations easier), the second one will be 1 tick slower, which is less than a nanosecond.
Here is a test where I run the comparison 10000 times.
The difference is pretty much non-existant.
There is no significant difference in efficiency, even if you have more than one of these preconditions in your function. No matter what language you use. Some compilers will probably even generate the same machine instructions from both versions.
Stop thinking about efficiency too much. Think about readability and maintainability!
It depends on the use case here, I don't think there is much difference in the context of performance or code readability.
I would personally go with the second approach as it also reduces indentations. Indentation gives me a clear indication of initialization of newer block. If I notice a new indent, I would assume there should be a for loop here or an if statement.
If the code is part of the main flow or the most common flow, I wouldn't want that to be further indented.
Again, All this is my personal style guide rules which have helped me to be able to deduce the code logic faster.

What is the difference and benefits/drawbacks between object literals and functions that return an object inside an IIFE?

So to clarify the question, I understand what an IIFE and object literal is. However, I am unsure what the difference(s) is/are between these two examples (aside from the fact that one is a function and the other is an object literal):
Example 1:
(function(){
var myStuff = {
arbitraryValue: 42
}
return myStuff.arbitraryValue;
})();
Example 2:
(function(){
var myStuff = function() {
return {
arbitraryValue: 42
};
}
return myStuff().arbitraryValue;
})();
Both examples return the same results, and are called (almost) the same way. But:
1) What are the fundamental differences between them?
2) Is there a benefit to using one over the other?
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
5) Are either of these examples considered "best practice," or is there another option?
Many thanks in advance!
1) What are the fundamental differences between them?
The first (probably) uses less CPU cycles because it has one less function call and is less to write. It's also easier to understand so is likely easier to maintain.
2) Is there a benefit to using one over the other?
The first uses less code and is likely easier to understand and maintain.
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
Perhaps using get, a feature of JavaScriptâ„¢ but not ECMAScript.
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
Yes, though you haven't shown what is done with the returned value. In the example it disappears into the ether.
5) Are either of these examples considered "best practice," or is there another option?
"Best" infers a complarison with other things that are less preferred based on objective criteria. Without those criteria (which might be some of: speed, robustness, maintainability, support or other features, desirable or not) it can't be determined.
If you propose a circumstance where you'd like to use one or the other, advice can be given on whether there are better ways or not based on the criteria suggested (or others you may have) and in comparison to alternatives.

Is it good to make function in function using 'return'?

While I was investigating functions, I realised that I can create embedded functions. Firstly, I thought it may be useful for structuring code. But now I suppose it isn't good style of coding. Am I right? Here is an example.
function show () {
return function a() {
alert('a');
return function b() {
alert('b');
}
}
}
And I can call alert('b') using this string: show()();
In what situations is better to use this method and in what not?
Yes, this has many uses.
Currying
Firstly, you may want to use currying, where you encapsulate a function with a single argument with a function with many arguments. For example,
function getHandler(num){
return function(){
alert(num);
}
}
myElement.onclick=getHandler(1)
myOtherElement.onclick=getHandler(25)
anotherElement.onclick=getHandler(42)
onclick() cannot be given arbitrary arguments as it is called by the system. Instead of writing 3 different handlers that alert different numbers, this reduces the bloat by creating a function that can generate arbitrary handlers of the "alert a number" type. Of course, this is a rather simplistic example, but if one had to do something considerably more complicated than alert(), the benefits of currying are evident.
Efficiency
Another situation is when you have a complicated function that has one computationally-heavy portion, which is followed by a computationally-light portion. The two portions take different parameters, and usually the parameters for the first portion will be the same. Some variation of memoization can be used to solve this, but function-as-return value works too.
For example, let's say you have a function of the following form:
function doSomething(a,b,c,x,y){
//Do some complicated calculations using a,b,c, the results go to variables e,f,g
//Do some simple calculations using e,f,g,x,y, return result
}
If I want to run doSomething(1,2,3,18,34)+doSomething(1,2,3,55,35)+doSomething(1,2,3,19,12), it would take 3 times the execution time as the long part is execute every time.
However, we can write it as:
function doSomethingCreator(a,b,c){
//Do some complicated calculations using a,b,c, the results go to variables e,f,g
return function(x,y){
//Do some simple calculations using e,f,g,x,y, return result
}
}
Now, all I need to do is call doSomethingCreator() for my set of parameters, and use the created function (which is fast) to get the final results. The code becomes:
var doSomething123=doSomethingCreator(1,2,3);
console.log(doSomething123(18,34)+doSomething123(55,35)+doSomething123(19,12))
One example of this is solving differential equations. Differential equations do not have a single solution if some "boundary conditions" are given. However, (especially for homogenous equations), after one point it is easy to vary the boundary conditions and get solutions. And usually one needs to solve the same equation for different boundary conditions multiple times. So, if you want to write a library method, you would have it take the homogenous equation as the input, and it would return a function, which in turn can be given the boundary conditions as an input to get the final solution.
"Static" variables via closures
Sometimes, you want to be able to easily create a set of variables and carry them around.
For example, if you want to create a counter function:
function generateCounter(){
var c=0;
return function(){
c++;
return c;
}
}
We can use this to make many independent counters, for example:
myCtr1=generateCounter();
myCtr2=generateCounter();
myCtr1(); //Returns 1
myCtr1(); //Returns 2
myCtr2(); //Returns 1
myCtr1(); //Returns 3
myCtr2(); //Returns 2
Each counter is independent. Of course, in this case, it would be easier to jut use myCtr1=0;myCtr2=0 and then the ++ operator, but what if you want to record the times when they were incremented? Extending the ++ case would involve a lot of code duplication, however, here we can tweak it pretty easily:
function generateCounter(){
var c=[]; // The length of c is the value of the counter
return function(){
c.push((new Date()).getTime());
return c;
}
}
When you should not use it
Whenever there is no obvious gain in doing so.
Aside from when you want to use it for closure-bound variables, there usually isn't much point in doing it with 0 arguments for the outer function as the inner function becomes the same function. See if it really improves the program, and then use it.
This is one of the most common styles of coding in Javascript and some other languages which treat their functions as first class citizens. One of the most uses of these nested declarations is in creating closures and currying.

Best way to code a single line if statement [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been writing in JavaScript for the last 5 years and am all self taught. The one problem I have come across as I meet more and more programmers. I find that I am not always coding things the best way possible.
I have been trying to figure out what is the best way to program a single line if statement in JS. I do not care about readability and the project is not open source, so I am not worried about others adding to it.
How I usually write my statements
condition = true;
if (condition)
runFunction();
else
runSecondFunction();
But I have found that everyone keeps telling me to use the brackets. I have been writing this off because they always throw in the following line as well "It makes it easier to read"
condition = true;
if (condition) {
runFunction();
}else{
runSecondFunction();
}
And lastly someone finally said to me that I should write the if statements to more closely match how they I written in C# which looks like the following
condition = true;
if (condition)
{
runFunction();
}
else
{
runSecondFunction();
}
And of course there is the shorthand, but I usually only use it for toggling variables like this
condition = true;
(condition) ? condition = false : condition = true;
but would it be better to use the shorthand for regular if statements as well. For example:
condition = true;
(condition) ? runFunction() : runSecondFunction();
So the question is
Out of all of the many ways to write a single line of JavaScript which is the best way to program it to run the fastest. I do not care about readability, so please don't say it is recommend to write it this way or that way because it is easier to read. Please also cite examples of why one way is faster or slower than another.
TO BE CLEAR
It is not that I don't care about readability is that none of those if statements are hard for me to read, they do make sense to me in all versions. So what some of you may consider hard to read I may not. This is what brings me to my next point, since none of those are hard for me to read, maybe I should write it the best way for JS to handle it.
For example I found that JS takes longer to run
counter++;
then it does
counter = counter + 1;
So finally to be clear I don't have a problem to reading any of these and I would just like to know which is best for JS to handle.
Take look at some jsperf tests:
braces vs no braces
ternary vs if
if vs boolean
They all seem to be relatively equal (aside from the boolean version being slower in the test I just ran), so I would go with whatever you like the look of best.
Your shorthand can be shortened:
Instead of:
(condition) ? condition = false : condition = true;
Try:
condition = condition ? false : true;
var a = condition ? 'conditionTrueValue' : 'conditionFalseValue';
// Or in this case, since you're just toggling the boolean:
condition = !condition;
Instead of:
(condition) ? runFunction() : runSecondFunction();
You can save a few characters like this:
(condition ? runFunction : runSecondFunction)();
Now, the performance difference on this, if any, is going to be insignificant.
Make your code readable. You'll be glad you did if you have to get back to your code in a year.
I usually get annoyed by convetion to put every curly bracket in seperate line, and I dont like that closing curly bracked has something afterwards. In addition, I dont like when they are not used at all.
This would me by way.
condition = true;
if (condition) {
runFunction();
}
else {
runSecondFunction();
}
When question is about terniary, then I have to say, that I use it only when there are no functions involved in conditions or results.
result = (number == 521 : "equal to 521" : "some other number");
I care about readability of my code, it matters, when you have file with many thousand lines of code, that looks quite similar - it is hard to debug or upgrade code, if it is unreadable.
If you 'truely' don't care about readability/maintainability then just write it the way that feel the most comfortable.
From my experience programming, the reason why people recommend using the the braces is really for maintainability, when someone has to add a block of code for the if statement, one argument was that if you type it once, you won't have to remember to insert it when you need a block of code rather than a single statement.
I recommend using the form below because Javascript has some quirks with braces (from memory), I believe it was to do with the concept of closure/functions) certain codes won't run. It caught me by surprised when I was debugging my broken code and then I read up on it but that was a long time ago.
if (expression) {
}
As for the performance factor, I believe that is more to do with the logic and code that is being executed and not the way you write the if statement.

In javascript what does ( ... ) do exactly [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
Recently discussing with a colleague which is best
(function(){...}())
or
(function(){...})()
I got to wondering what ( ... ) actually does at a fundamental level, and what is the difference between what the js engine does in both the above cases. Is one approach theoretically (even if only a tiny amount) faster than the other? If my function returns an object what does ( .. ) do to the object in the first example?
Can anyone explain.
*edit The closest I've got to an explanation on the internet is http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#question-about-surrounding-parentheses, but this stops short, in my view, of explaining why the first example above works at all.
You don't even need parentheses at all. The whole idea of those parentheses is to force a function to be an expression and not a declaration. You can also achieve that like
!function() {
}();
That exclamationmark could also be + or - and some other characters. So, it makes no difference whether you are using the "dog balls" version (your latter one) or not. From a performance aspect, I can't guarantee but I'm 99.9% sure there is zero difference (maybe engine dependent variation at best).
So if we assume that there is no performance difference between those two, its pretty much personal preference which one you use. The Crock many times declared the second version as "dog balls" because you don't wrap the whole expression anymore. I'd agree on that. As mentioned before, the pattern does just force a function expression and it should encapsulate the whole thing for a better readability.
The first example works for exactly the same reason the second example works. There's no real difference. This also works:
!function() { ... } ();
So does this:
var _dont_care_ = function() { ... } ();
The key is to arrange for the function keyword to appear in the statement at a point where the parser knows that it cannot be the start of a function declaration statement. In such cases, the function keyword must be instantiating a function object as a value in an expression.
Statements in JavaScript other than expression statements start with keywords (leave labels aside for the moment). Inside any statement that doesn't start with the function keyword (going out on a limb here), the only thing that function can mean is the instantiation of a function object value.

Categories