I am comparing data that can have only 3 possible results, less than, greater than, or equal to.
Hence the last statement could be an else or an else / if, and the block would behave the same:
if(iter.data === data) {
return iter;
} else if(data < iter.data) {
iter = iter.left;
// else or else if will suffice here
} else if(data > iter.data) {
iter = iter.right;
}
Is there any functional difference I am missing, or is this simply a matter of style?
Is there a good style reference, that covers this if it is only a matter of style?
The compiler/interpreter won't care and will optimize these regardless, but from a mental load standpoint else if implies another comparison, whereas else implies a "fall-through" and most codebases will prefer the latter.
As an added bonus, the fall-through also ensures that one of the branches is always taken. Generally speaking, no branches being taken at all could potentially lead to much weirder bugs than the wrong branch being taken.
Just for fun, let me add:
switch (true){
case iter.data === data: return iter;
case iter.data > data: iter = iter.left; break;
case iter.data < data: iter = iter.right; break;
}
With the example, I probably would do this though:
if (iter.data === data) {
return iter;
}
iter = (iter.data > data) ? iter.left : iter.right;
It highlights the different behavior between the branches (return vs assignment), which for me is the most important thing to recognize. And it even has the least lines of code.
But yes, it is a matter of taste.
Would something like this work? check for less and greater but returns the default if both fail.
//if/else
if(data < iter.data) {
return iter.left;
}
if(data > iter.data) {
return iter.right;
}
return iter;
DanDavis suggested ternary so maybe this?
//ternary example
return data < iter.data ? iter.left : (data > iter.data ? iter.right : iter);
Related
I have some functionality dependent on many conditions. All variables in conditional statements are boolean variables and the code is the following and I don't like it:
if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Is there a way to make it more understandable and nice?
That's about as concise as you're going to get with JavaScript. I suppose if you really wanted to, you could create variables to store your binary options:
var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;
if (multiMarketOneSelected || singleMarketMultiAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Though I don't really know if you gain much readability from that.
Your code seems fine, but if you don't like it you could do something like this (note that the only improvement here is style, if you like it better):
function check(){
return {
valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
case: [
isOnlyAgencySelected,
noAgencySelected && isOnlyMarketSelected
]
};
}
var conditions = check();
if (conditions.valid) {
if (conditions.case[0]) {
//do case 1
} else if (conditions.case[1]) {
//do case 2
}
}
Some things I would try to make the code more readable:
Initialise the variables in a way that you don't have to negate them again. So !userHasMoreThanOneMarket becomes userHasOneMarket
isOnlyMarketSelected sounds redundant to me. And you are checking it in the outer if-clause and the inner again.
You probably have a lot of code above this code snippet to initialise and set all this boolean values. Try return; statements after each variable to get rid of if-conditions.
I hope this helps.
after days of hard thinking i choose to ask that question. I have if statement with multiple conditions:
//var current is array of arrays of integers
if((current[rot][0] + x)<blocks.length
&& (current[rot][1] + x)<blocks.length
&& (current[rot][2] + x)<blocks.length
&& (current[rot][3] + x)<blocks.length
&& !$(blocks[current[rot][0]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][1]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][2]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][3]+x]).hasClass("blockLand"))
{
//something to happen here ONCE!
}
Because i want something inside to happen just once i think i cant use for loop.
So my question is: is there a possible way to reduce the conditions number? and how?
P.S.: Yes i figured out that i can use flag (true/false) inside and do my stuff outside this if, in another if - but i think that not always gonna work, because for every loop the flag will be different.
var b = true;
for (var i = 0; i <= 3; i++) {
// In two lines for being clear, but it's possible just in one
b = b && (current[rot][i] + x)<blocks.length
b = b && !$(blocks[current[rot][i]+x]).hasClass("blockLand");
// You could speed it up this way.
if(!b) break;
}
if (b) {
//something to happen here ONCE!
}
I think I understand what you are asking but let me know if there is anything else I can do.
JavaScript has a ternary (conditional operator) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This operator allows you to assign true/false values based on an internal if/else condition.
Here is some code for you to explain this...
window.onload = function() {
var one = 1;
var two = 2;
console.log(one > two ? "greater" : "not greater");
};
You can also use a Switch statement which you can read about here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch.
Here is an example of a switch statement.
window.onload = function() {
var string = "testing this out";
switch (string) {
case "testing this out":
console.log('testing this out found in condition one');
break;
case "testing":
console.log('found testing');
break;
default:
console.log('not found');
break;
}
};
Let me know if I can improve this.
I want to exit from the below if block in Javascript. if I return, then it does not check for the next if condition. How do I do that?
if ($('#id1').length > 0) {
if(yester_energy == "NaN" || yester_energy == 0){
//break from #id1
}
else{
//something
}
$("#abc").html(somthing)
}
if ($('#id2').length > 0) {
if(yester_energy == "NaN" || yester_energy == 0){
//break from #id2
}
else{
//something
}
}
Super late to the party, but for folks from search, you can use something called labeling. It's not good practice, but in rare cases that can be applied. Basically you can assign a name to the if statement that you want to break from. And anywhere in statement call break from specified name.
Code example:
my_if: if (condition) {
// do stuff
break my_if;
// not do stuff
}
in your particular case:
id1: if ($('#id1').length > 0) {
if(yester_energy == "NaN" || yester_energy == 0){
break id1;
}else{
//something
}
$("#abc").html(somthing)
}
More about labeling can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label#Syntax
Even later to the party... Typically in such situations, I use a combination of if and do...while as follows...
if ( condition ) do {
// processing
if ( exit_condition ) break;
// more processing...
} while ( false );
Thus, when the break is encountered, it applies to the do...while loop, and processing continues after the while, effectively breaking out of the outer if statement...
All your code after if(isNaN(yester_energy) || yester_energy == 0) is in else block, so it'll not be executed if your data matches this if. And you just don't need anything else.
Also, if you want to check if variable got NaN value, then use isNaN() function. You can't just compare it.
Use switch statment,
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
you can use function and pass command
function iff(condition){
if(condition ==0) return;
console.log("other commands")
}
iff(0);
iff(1)
Don't Use Labeling
You can do labeling as the other answer suggests, but it smells odds and it will definitely come up in code review. It will confuse readers of your code and increase the maintenance burden of your codebase.
Answer
Best is to refactor (extract out) the code inside the if-statement into a separate function that you can then return from. In addition to allowing you to exit from the code block early, it also makes your code more modular and readable.
Example (based on OP)
if ($('#id1').length > 0) {
ifInner(yester_energy)
$("#abc").html(somthing) // [sic]
}
if ($('#id2').length > 0) {
ifInner(yester_energy)
}
// Rename to something more descriptive.
function ifInner(yester_energy) {
if (yester_energy == "NaN" || yester_energy == 0){
// Break out.
return;
}
else {
// something
}
}
Adding another answer to the pool, in many cases using a try catch makes perfect sense:
if(something is allowed) {
try {
if(missing requirements) throw 'missing requirements'
//do your stuff;
}
catch {
//you may do logging and issue warning here
}
}
I have the following situation:
IF condition THEN
IF condition THEN
sequence 1
ELSE
break //?
ENDIF
ELSE
sequence 3
ENDIF
What is the result of the break statement? Does it break the outer if statement? Because this is what I actually need.
If you label the if statement you can use break.
breakme: if (condition) {
// Do stuff
if (condition2){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
You can even label and break plain blocks.
breakme: {
// Do stuff
if (condition){
// do stuff
} else {
break breakme;
}
// Do more stuff
}
It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.
( function() {
// Do stuff
if ( condition1 ) {
// Do stuff
} else {
return;
}
// Do other stuff
}() );
no it doesnt. break is for loops, not ifs.
nested if statements are just terrible. If you can avoid them, avoid them. Can you rewrite your code to be something like
if (c1 && c2) {
//sequence 1
} else if (c3 && c2) {
// sequence 3
}
that way you don't need any control logic to 'break out' of the loop.
But there is switch-case :)
switch (true) {
case true:
console.log("Yes, its ture :) Break from the switch-case");
break;
case false:
console.log("Nope, but if the condition was set to false this would be used and then break");
break;
default:
console.log("If all else fails");
break;
}
In the most languages, break does only cancel loops like for, while etc.
To make multiple checking statements more readable (and avoid nested ifs):
var tmp = 'Test[some.email#somewhereouttherebutnothere.com]';
var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;
do {
if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }
posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');
if (posStartEmail === -1 || posEndEmail === -1) { break; }
email = tmp.substring(posStartEmail+1+4,posEndEmail);
if (email.indexOf('#') === -1) { break; }
// all checks are done - do what you intend to do
alert ('All checks are ok')
break; // the most important break of them all
} while(true);
Javascript will throw an exception if you attempt to use a break; statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.
JSFiddle
Actually there is no c3 in the sample code in the original question. So the if would be more properly
if (c1 && c2) {
//sequence 1
} else if (!c1 && !c2) {
// sequence 3
}
I had a similar problem today and found refactoring the conditional logic into a separate function to help.
I find it more readable than the labels and people are more comfortable with return than break. Inline functions are similar but the indentation can get a bit confusing.
In your case it would look like this.
function doThing() {
checkConditions();
// Rest of the code here
}
function checkConditions() {
if (c1) {
if (c2) {
return do1();
else {
return;
}
} else {
return do3();
}
}
Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.
You need that it breaks the outer if statement. Why do you use second else?
IF condition THEN
IF condition THEN
sequence 1
// ELSE sequence 4
// break //?
// ENDIF
ELSE
sequence 3
ENDIF
sequence 4
How can I achieve an elseif in a JavaScript condition?
In JavaScript's if-then-else there is technically no elseif branch.
But it works if you write it this way:
if (condition) {
} else if (other_condition) {
} else {
}
To make it obvious what is really happening you can expand the above code using an additional pair of { and }:
if (condition) {
} else {
if (other_condition) {
} else {
}
}
In the first example we're using some implicit JS behavior about {} uses. We can omit these curly braces if there is only one statement inside. Which is the case in this construct, because the inner if-then-else only counts as one statment. The truth is that those are 2 nested if-statements. And not an if-statement with 2 branches, as it may appear on first sight.
This way it resembles the elseif that is present in other languages.
It is a question of style and preference which way you use it.
Just add a space:
if (...) {
} else if (...) {
} else {
}
You could use this syntax which is functionally equivalent:
switch (true) {
case condition1:
//e.g. if (condition1 === true)
break;
case condition2:
//e.g. elseif (condition2 === true)
break;
default:
//e.g. else
}
This works because each condition is fully evaluated before comparison with the switch value, so the first one that evaluates to true will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.
Note that strict comparison is used, so a branch whose condition is merely "truthy" will not be executed. You can cast a truthy value to true with double negation: !!condition.
Actually, technically when indented properly, it would be:
if (condition) {
...
} else {
if (condition) {
...
} else {
...
}
}
There is no else if, strictly speaking.
(Update: Of course, as pointed out, the above is not considered good style.)
if ( 100 < 500 ) {
//any action
}
else if ( 100 > 500 ){
//any another action
}
Easy, use space
Conditional statements are used to perform different actions based on different conditions.
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9')
You are missing a space between else and if
It should be else if instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}