'if/else' vs 'if' for performance and readability? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've recently started using Snippet 2 instead of Snippet 1, for basic selection statements. This seems a bit un-conventional, so I wanted to know if there is performance difference, or if one seems more readable than the other.
Snippet 1
function foo() {
if(case1){
//...
} else if (case2) {
//...
} else if (case3) {
//...
} else{
// catch other cases
}
}
Snippet 2
function foo() {
if(case1){
//...
return;
}
if(case2){
//...
return;
}
if(case3){
//...
return;
}
// catch other cases
}

Your snippets are the same thing. But I'd use elseif even if I return. It kind of gives me a sense that those if statements are related and helps me with readability.
if ... else also helps in performance, let's say, when you're if-ing the same variable. Why test a condition if the previous one succeeded? elseif it so it won't try again.
It's a matter of design. It depends on what you want to achieve so there's no EXACT BEST way of doing it. It's all a matter of how you need to exit your code block that contains the ifs.

The Ifs alone mean that all of the conditions can possibly happen - they'll be checked one by one. The chained if-else statements mean that only one of the conditions can actually happen - if one of the conditions get executed, I believe it skips over all of the rest. Most languages support a switch statement as well, which would be somewhat more readable than chaining together a bunch of if-else-if statements. Correct me if I'm wrong, but I believe this applies in every language I've used so far.
Edit: In this particular case (as pointed out by some others below - thank you), all of the conditions cannot happen because of the return statements in each of the if statements. In a more general case though, my explanation still holds.

It depends on your needs. As a general rule, the more exit points you have to a function, the harder it is to read. That said, there is often benefit of
if(somehting)
{
// one liner;
return;
}
if(something else)
{
// 30 lines of something else.
return;
}
// catchall
instead of:
if(something)
{
// one liner;
return;
}
else if(something else)
{
// now nested! 30 lines.
return;
}
Chances are, though, that you could probably make things even easier to read by turning those conditions into their own functions. Wouldn't this be nice:
if(something)
{
doSomething();
}
else if(something else)
{
doSomethingElse();
}
else
{
doJustElse();
}
The benefit of the last one? Succinct, clear, clean, obvious, and a low learning curve.

If you have too many else if statements then it always better to use switch rather than using if.

Snippet 1 is going to be better for performance when you don't need case 3 to be satisfied, since the other else if will not be fired. However, if you have a lot of other else if, you should use a switch

Related

Is it good practice to surround code with braces? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Is it okay to surround code with braces { } for making code in IDE's compress/collapse?
For example:
{
function foo(a,b) {
return a*b+b;
}
function bar(a,b,c) {
return a*b+c;
}
}
This would collapse in my IDE to the following:
{ ...
}
Are these extra braces allowed, or would it be syntactically incorrect? (I know it works because the code has run without any errors regarding syntax.)
You've already answered your question:
Are these extra braces allowed, or would it be syntactically incorrect?
with
(I know it works because the code has run without any errors regarding syntax)
It is syntactically permitted, as of ES2015.
But, these sorts of plain blocks have some issues:
Function declarations inside them work very strangely (so using them is likely to confuse people in some circumstances)
They're quite unusual to see - generally, script-writers do not use them, and do not expect them, so using such a block is likely to confuse some
If you need the ability to "compress" code - to group parts of related code without cluttering up a script - consider using modules instead. For example
// fooAndBar.js
export function foo(a, b) {
return a*b+b;
}
export function bar(a, b, c) {
return a*b+c;
}
Then just import the functions when needed.
It's a lot easier to maintain and debug 8 files that are 50 lines each than it is to do the same for one file that's 400 lines each. If you have to collapse blocks to make something easier to read, it's probably time to refactor to another file.

Multiple if statements with locks [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have multiple if statements like this:
if (variable == something && lock01 == false)
{
do your thing
lock01=false; lock02=true; lock03=true; ....
}
else
{
lock01=true; lock02=false; lock03=true;
}
This locks all other if statements so only one is active at a time. The problem with this is if I add more if statements, I have to add more locks by hand. It also only works from top to bottom one after another. Is there a better way to do this? If it's easier in Jquery, JQ code is also ok.
edit: I forgot to write that I loop through the if statements and only one can be unlocked at a time.
One option would be to use a variable that identifies which lock is unlocked:
unlocked = "lock01";
// or
unlocked = 1;
Then your code could look something like this:
if (variable == something && unlocked === 1) {
// do your thing
} else {
unlocked = 2;
}
Probably the best thing to do is to use switch statements instead of "n" if/else statements.
So you code will looks like:
switch(variable) {
case 1:
do your things here;
break;
case 2:
do something else;
break;
case 3:
case 4:
when variable is 3 or 4 do the same code
break;
default:
do something else;
lock = false;
}
and so on.
Switch statements works with strings or numbers (as far as I know), just make sure to use quote with strings (e.g.: case 'something').
If you don't want to use switch statements, then use else/if:
if(variable == something) {
do something;
}
else if(variable == something_else) {
do something_else;
}
else {
lock = false
}
This way only the first matched "if" will be executed.

JavaScript: Is it allowed to use a `ternary` statement inside an `if` statement? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In the following script, I've used a ternary statement in the else if portion of an if statement, juxtaposing the two. In a case like this, should I substitute another if statement inside the else if?
var attackOpt = prompt('Which attack option does Angelo use in this turn?');
// Remaining number of times Angelo can cast spells:
var angMP = 3;
// Validity Check to see if the attack option entered can be executed:
while (true) {
if (attackOpt === 'slash') {
break;
}
else if (attackOpt === 'magic') {
(angMP) ?
break;
: attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
}
Yes, it will work but it makes the code difficult to read. Consider revision to your 'while' loop instead:
while (attackOpt !== 'slash' && angMP) {
attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
Of course, this is a stylistic choice and entirely up to you.
Yes, you can have a ternary operator expression (it's not a statement) anywhere an expression is allowed.
But a ternary operator uses expressions as its 3 arguments. break is not an expression, but a statement. You can't use break there.
You'll have to use an if statement.
You cannot do this. It will result in syntax error and the code won't run. Ternary operator is used to return values quickly without if-else. No breaks are allowed. However, you can use something like that, in a single line:
if (angMP) break; else attackOpt = prompt('Angelo can no longer cast spells. Select again.');
Or even the simpler form in other parts of your code:
if (angMP) break;
not needed it will work properly without any problem
(angMP) ? break : attackOpt = prompt('Angelo can no longer cast spells. Select again.');

Javascript appears to be saying true == false [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following js function.
function showAttentionItem(sender)
{
debugger;
var assistanceRequired = sender.parent().hasClass("assistanceRequired");
if (assistanceRequired)
{
sender.children('.assistanceRequiredText').fadeToggle(0);
if (sender.children('.assistanceRequiredText').is(":visible"))
{
sender.children('.studentPerformanceText').hide();
}
}
if (!assistanceRequired)
{
if (sender.parent().hasClass("studentOutsideTargetRange"))
{
sender.children('.studentPerformanceText').fadeToggle(0);
}
}
}
What happens when I run it is, I hit the debugger line, and step through the code. assistanceRequired is true.
After executing sender.children('.studentPerformanceText').hide();, the next line it jumps to is sender.children('.studentPerformanceText').fadeToggle(0);, inside the if (!assistanceRequired) statement!
How could this possibly be happening?
This is guaranteed to work:
if (sender.parent().hasClass("assistanceRequired"))
{
// do whatever here
}
else
{
// do whatever ELSE here
}
Only one or the other can ever run when coded correctly since there is only one test and it will either be true or false the single time it is tested. There is no possibility for it to be changed by some side effect you are not aware of, which is most likely what is happening. This is not debatable.
If this does not work the way you want then something else is wrong that you are not showing and without an executable jsFiddle good luck convincing anyone that a fundamental thing like the if ... else construct is broken.
I can think of only one scenario to explain what you are seeing.
There's a double trigggering of showAttentionItem(), which, in the debugger, is perceived as a single call. On the first call, assistanceRequired is true and on the second it's false.

javascript return when stopping function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
If I write this:
$('#SomeDiv').click(DoSomething);
function DoSomething() {
if (SomeCondition === true) {
return false;
}
// more code here
}
regardless of whether I put return; or return false; or return true; the code doesn't throw exceptions and the function execution stops.
Which is the best option?
If those are the only options, use return; in this case. (read below)
If the function normally returns something (calculates something, gets some value, etc) then you definitely don't want to return anything, because you might confuse the caller.
If your function doesn't normally return anything, then it might not hurt to return anything you like, but it might still confuse callers.
I would personally rather just put an else after the if, and not use the return;. And if the function gets too large, just retractor it a bit.
If you just want to stop the function on some condition and don't care what it returns, then it doesn't matter which of the three you choose. If you're not using the output of the function, I'd just use a simple return; statement to stop it executing further.

Categories

Resources