What are the differences between if, else, and else if? [closed] - c
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
I am trying to discern the difference between
if
else
else if
When do you use them and when not?
I have a homework assignment with a ton of instances and I am running into code error due to not knowing the differences between each.
Can someone please define how to use these?
An if statement follows this sort of structure:
if (condition)
{
// executed only if "condition" is true
}
else if (other condition)
{
// executed only if "condition" was false and "other condition" is true
}
else
{
// executed only if both "condition" and "other condition" were false
}
The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."
You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.
If-elseif-else can be written as a nested if-else. These are (logically speaking) equivalent:
if (A)
{
doA();
}
else if (B)
{
doB();
}
else if (C)
{
doC();
}
else
{
doX();
}
is the same as:
if (A)
{
doA();
}
else
{
if (B)
{
doB();
}
else
{
if (C)
{
doC();
}
else
{
doX();
}
}
}
The result is that ultimately only one of doA, doB, doC, or doX will be evaluated.
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
:)
If, else and else if are all constructs to help 'branch' code. Basically, you employ them whenever you want to make a decision.
An example would be 'if it's sunny, I'll go outside. otherwise, I'll stay inside'
In code (ignoring the extra stuff)
if (sunny) {
goOutside();
}
else {
stayInside();
}
You CAN use 'else if' statements if you want to add 'additional' conditions. Extending the previous example, "if it's sunny, I'll go outside. If it's stormy, I'll go into the basement otherwise I'll stay inside"
In code
if (sunny) {
goOutside();
}
else if (stormy) {
goDownstairs();
}
else {
stayInside();
}
EDIT section:
Here is how you can write multiple ifs as and conditions. The following example can be written in at least two ways:
'If it's sunny and warm, go outside. If it's sunny and cold, do nothing'
if (sunny) {
if (warm) {
goOutside();
}
else if (cold) {
doNothing();
}
}
OR
if (sunny && warm) {
goOutside();
}
else if (sunny && cold) {
doNothing();
}
There's no "else if". You have the following:
if (condition)
statement or block
Or:
if (condition)
statement or block
else
statement or block
In the first case, the statement or block is executed if the condition is true (different than 0). In the second case, if the condition is true, the first statement or block is executed, otherwise the second statement or block is executed.
So, when you write "else if", that's an "else statement", where the second statement is an if statement. You might have problems if you try to do this:
if (condition)
if (condition)
statement or block
else
statement or block
The problem here being you want the "else" to refer to the first "if", but you are actually referring to the second one. You fix this by doing:
if (condition)
{
if (condition)
statement or block
} else
statement or block
Dead Simple Pseudo-Code Explanation:
/* If Example */
if(condition_is_true){
do_this
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-Else Example */
if(condition_is_true){
do_this
}else{
do_this_if_condition_was_false
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-ElseIf-Else Example */
if(condition_is_true){
do_this
}else if(different_condition_is_true){
do_this_only_if_first_condition_was_false_and_different_condition_was_true
}else{
do_this_only_if_neither_condition_was_true
}
now_do_this_regardless_of_whether_condition_was_true_or_false
I think it helps to think of the "else" as the word OTHERWISE.
so you would read it like this:
if (something is true)
{
// do stuff
}
otherwise if (some other thing is true)
{
// do some stuff
}
otherwise
{
// do some other stuff :)
}
if (condition)
{
thingsToDo()..
}
else if (condition2)
{
thingsToDoInTheSecondCase()..
}
else
{
thingsToDoInOtherCase()..
}
you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions
go with an umbrella
go without an umbrella
and both the two actions are bound to one condition, i.e is it raining?
now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.
They mean exactly what they mean in English.
IF a condition is true, do something, ELSE (otherwise) IF another condition is true, do something, ELSE do this when all else fails.
Note that there is no else if construct specifically, just if and else, but the syntax allows you to place else and if together, and the convention is not to nest them deeper when you do. For example:
if( x )
{
...
}
else if( y )
{
...
}
else
{
...
}
Is syntactically identical to:
if( x )
{
...
}
else
{
if( y )
{
...
}
else
{
...
}
}
The syntax in both cases is:
if *<statment|statment-block>* else *<statment|statment-block>*
and if is itself a statment, so that syntax alone supports the use of else if
if (numOptions == 1)
return "if";
else if (numOptions > 2)
return "else if";
else
return "else";
The syntax of if statement is
if(condition)
something; // executed, when condition is true
else
otherthing; // otherwise this part is executed
So, basically, else is a part of if construct (something and otherthing are often compound statements enclosed in {} and else part is, in fact, optional). And else if is a combination of two ifs, where otherthing is an if itself.
if(condition1)
something;
else if(condition2)
otherthing;
else
totallydifferenthing;
The if statement uses the results of a logical expression to decide if one of two code blocks will be executed.
With this code
if (logical expression) {
code block 1;
} else {
code block 2;
}
if the logical expression is true, only the statements in code block 1 will be executed; if false, only the statements in code block 2.
In the case that there are multiple similar tests to be done (for instance if we are testing a number to be less than zero, equal to zero or more than zero) then the second test can be placed as the first statement of the else code block.
if (logical expression 1) {
code block 1;
} else {
if (logical expression 2) {
code block 2;
} else {
code block 3;
}
}
In this case, code block 1 is executed if logical expression 1 is true; code block 2 if logical expression 1 is false and logical expression 2 is true; code block 3 if both logical expressions are false.
Obviously this can be repeated with another if statement as the first statement of code block 3.
The else if statement is simply a reformatted version of this code.
if (logical expression 1) {
code block 1;
} else if (logical expression 2) {
code block 2;
} else {
code block 3;
}
The else if can be used in conjunction with 'if', and 'else' to further break down the logic
//if less than zero
if( myInt < 0){
//do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10
//do something
}else{
//else all others
//do something
}
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do.
The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
If and else if both are used to test the conditions.
I take case of If and else..
In the if case compiler check all cases Wether it is true or false.
if no one block execute then else part will be executed.
in the case of else if compiler stop the flow of program when it got false value. it does not read whole program.So better performance we use else if.
But both have their importance according to situation
i take example of foor ordering menu
if i use else if then it will suit well
because user can check only one also.
and it will give error
so i use if here..
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
now else if case
if (time < 12) {
greeting = "Good morning";
} else if (time < 22) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
here only satisfy one condition..
and in case of if multiple conditions can be satisfied...
What the if says:
Whether I'm true or not, always check other conditions too.
What the else if says:
Only check other conditions if i wasn't true.
Related
how do i rewrite this ternary operator in C?
How do I write in a loop instead of a ternary operator ? temp->status = (inStore ? waiting : called); would it be like: if (inStore){ return waiting; } else ( return called; } I'm unsure becauseI get an error doing this, I'm using it in a void function
The problem is here: else (. Change the ( to { and your compile should be clean. The ternary operator is simply an if-then-else statement in a shortcut syntax, with the assignment statement presented as its single lvalue. So: temp->status = (inStore ? waiting : called); is translated to: if(inStore == true) { temp->status = waiting; } else { temp->status = called; } Note that there is nothing wrong with your syntax (except maybe the "(" here: else (). In a function, it might be preferable to use return statements if the function required no clean up before leaving.
You have to assign waiting or called to temp->status variable instead of returning it, also in else you used parenthesis wrongly. Whole thing should be: if (inStore) temp->status = waiting; else temp->status = called; I am not sure why you asked for a loop in that case, as there is no need to use one.
if(inStore){ temp->status = waiting; } else { // there was a ( instead of a { temp->status = called; }
How can I write an if thats related to a single else, then beneath it an if that is related to a different else?
I want to relate each if statement to the else one below it only. So when the if isn't true the else beneath it is active alone. Then the next if will be run, and the else below that one will be used if its FALSE. How can I do this? if (.....){ } else (....){ } if (.....){ } else (....){ } if (.....){ } else (....){ }
You could use the ternary operator in C. The syntax is as follows result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;
The most straight-forward way of solving this would be to simply exit once you've have entered any if...else block. You can do this with either a return statement inside each conditional, or a break. As long as all of your conditionals are within a loop or outer block, this will bypass your other if...else statements. For example: if (a) { return b + 1 } else { return b + 2 } or: if (a) { b += 1 break } else { b += 2 break }
Elegant way for do ... while in groovy
How to do code something like this in groovy? do { x.doIt() } while (!x.isFinished()) Because there is no do ... while syntax in groovy. No 'do ... while()' syntax as yet. Due to ambiguity, we've not yet added support for do .. while to Groovy References: groovy - dev > do while Migration From Classic to JSR syntax Groovy Documentation > Control Structures > Looping Rosetta Code > Loops/Do-while Groovy
You can roll your own looping that's almost what you want. Here's an example with loop { code } until { condition } You can't have a corresponding loop { code } while { condition } because while is a keyword. But you could call it something else. Anyway here's some rough and ready code for loop until. One gotcha is you need to use braces for the until condition to make it a closure. There may well be other issues with it. class Looper { private Closure code static Looper loop( Closure code ) { new Looper(code:code) } void until( Closure test ) { code() while (!test()) { code() } } } Usage: import static Looper.* int i = 0 loop { println("Looping : " + i) i += 1 } until { i == 5 }
So many answers and not a single one without a redundant call, a shame ;) This is the closest it can get to purely language syntax based do-while in Groovy: while ({ x.doIt() !x.isFinished() }()) continue The last statement within curly braces (within closure) is evaluated as a loop exit condition. Instead of continue keyword a semicolon can be used. Additional nice thing about it, loop can be parametrized (kind of), like: Closure<Boolean> somethingToDo = { foo -> foo.doIt() !foo.isFinished() } and then elsewhere: while (somethingToDo(x)) continue Formerly I've proposed this answer over here: How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?
Depending on your use case, there are options like this: do .. while() in Groovy with inputStream? Or you can do: x.doIt() while( !x.finished ) { x.doIt() } Or while( true ) { x.doIt() if( x.finished ) break }
You can use a condition variable with the regular while loop: def keepGoing = true while( keepGoing ){ doSomething() keepGoing = ... // evaluate the loop condition here }
Update Groovy 2.6 has been abandoned to concentrate on 3.0. From Groovy 2.6 on, do-while is supported when enabling the new Parrot Parser, from Groovy 3.0 on this is the default. See release notes: // classic Java-style do..while loop def count = 5 def fact = 1 do { fact *= count-- } while(count > 1) assert fact == 120
By now, Groovy has support for do/while: do { x.doIt() } while (!x.isFinished())
Or you can implement it in a Groovier way : def loop(Closure g){ def valueHolder = [:] g.delegate = valueHolder g.resolveStrategy = Closure.DELEGATE_FIRST g() [until:{Closure w -> w.delegate = valueHolder w.resolveStrategy = Closure.DELEGATE_FIRST while(!w()){ g() } }] }
Else-part of code being executed, even if string.equals(otherstring) is true
The problem with this code seems to be that the 'else' part of the if-statement is executed, even if the variables match (so 'if' is true). Any advice, please? Thanks! public void CheckInstalledDBVersion() throws NullPointerException, IOException { try { //TRY TO OPEN DATABASE AND READ VERSION //WRITE VERSION TO InstalledDBversion } catch(RuntimeException e) { //IF TABLE COULD NOT BE QUERIED //SET InstalledDBversion to Bogus value InstalledDBversion = "00"; Log.d("RTE", ".. but we've catched it!"); } finally { if (InstalledDBversion.equals(PackedDBversion)){ // Installed DBVersion == Packed DBVersion .. nothing happens } else showDialog(DBCHECKFAILDIALOG); initialiseDatabase = false; copyDB(); } } So, when I execute, copyDB(); gets called even if InstalledDBversion.equals(PackedDBversion) == true
else showDialog(DBCHECKFAILDIALOG); initialiseDatabase = false; copyDB(); Fixed indentation for you. copyDB is outside of the if/then/else block. Use an IDE with code formatting.
What lines are supposed to be included in the else block? the showDialog(DBCHECKFAILDIALOG) is only included. Are you missing a set of {} for the else block?
Which is better practice - for loop with break or conditional loop? [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 2 years ago. Improve this question I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop? The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax. for loop with break: var i:int; var isBaxterInMilwaukee:Boolean; for (i = 0; i < arrayLen; i++) { if (myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); break; } } conditional loop: var i:int; var isBaxterInMilwaukee:Boolean; while (!isBaxterInMilwaukee && i < arrayLen) { if (myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); } i++; }
In short, you should go with whichever version is the easiest to read and maintain. In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go. (This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.) I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing. If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother: bool isBaxterInMilwaukee; foreach (var item in myArray) { if (item.name == "baxter" && item.location == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); break; } } However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find. Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead): bool isBaxterInMilwaukee(Array myArray) { foreach (var item in myArray) { if (item.name == "baxter" && item.location == "milwaukee") { barkTwice(); return true; } } return false; } As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.) For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition: var i:int; var isBaxterInMilwaukee:Boolean; for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++) { if (myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); } } You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability: var i:int = -1; var isBaxterInMilwaukee:Boolean; while (!isBaxterInMilwaukee && ++i < arrayLen) { if (myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); } }
I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer. This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be. It's not an efficiency of operation thing, it's a maintainability thing. Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.
I would say it depends. In this case the loop with the break seems clearer to me.
In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way: var i:int; var isBaxterInMilwaukee:Boolean; isBaxterInMilwaukee = false; for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++) { if (myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee = true; barkTwice(); } } That way you don't need a break, and it's still more readable than a while loop.
There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops. In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like: while (counter <= end) { // do really cool stuff ++counter; } Then you are probably better off with a for loop since you are iterating. However, loops like: for (int tryCount=0; tryCount<2; ++tryCount) { if (someOperation() == SUCCESS) { break; } } should be written as while loops since they are really repeating something until a condition is true. The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.
The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this. Probably the best thing you want here is a modification of your while loop: while(!isBaxterInMilwaukee || i < arrayLen) { if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") { isBaxterInMilwaukee == true; barkTwice() } else { i++; } } That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression. ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...
I see the break in both loops, is that correct? Anyway: I would choose FOR loop when there is known number (maximum number) of iterations before loop starts. I would choose WHILE otherwise. In FOR loop I use BREAK freely. In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).
I would say break, clearer (even if you put in a comment why you break out of the loop) Imho the while loop is not clear, i would go for break
I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition. There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code! the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”? break statement is unnecessary if you're using a terminate-loop variable. Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.
There are two aspects of the problem: What to do (eg: find if one of the items contain the specified person in the location) How to do it (eg: use an index, iterate etc) Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern // what we are looking for? IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee"); // does the array contain what we are looking for? bool found = myArray.Find(item => condition.IsSatifiedBy(item)); // do something if the condition is satisfied if (found) { barkTwice(); } For completeness here is the class definition for the condition: class IsPersonInLocation { public string Person { get; set; } public string Location { get; set; } public IsPersonInLocation(string person, string location) { this.Person = person; this.Location = location; } bool IsSatifiedBy(item) { return item["name"] == this.Person && item["location"] == this.Location; } }
It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide. Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional. It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).
I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time. EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.
My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax). By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable. And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason. But consistency and clarity is the ovveriding consideration. YMMV, of course.
I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after. In JS: if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" })) barkTwice(); or with some utils of your own if(myArray.containsMatch({name:"baxter",location:"milwaukee"}) barkTwice();
Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded. Some example C# code: class Program { static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces) { foreach (WhoAndWhere personAndPlace in peopleAndPlaces) { if (personAndPlace.Name == "Baxter" && personAndPlace.Location == "Milwaukee") { return true; } } return false; } static void Main(string[] args) { List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>(); somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver")); somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee")); somePeopleAndPlaces.Add(new WhoAndWhere("George", "London")); if (IsBaxterInMilwaukee(somePeopleAndPlaces)) { // BarkTwice() Console.WriteLine("Bark twice"); } } public class WhoAndWhere { public WhoAndWhere(string name, string location) { this.Name = name; this.Location = location; } public string Name { get; private set; } public string Location { get; private set; } } }
My general stance is: If it has a loop counter use for() (like while while loop does).
I vote while because breaks reduce grokability. You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not. But I subscribe to the don't make me think model of coding.
In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true. let barkTwice = () => { console.log('bark twice'); } let arr = [{ location: "waukee", name: "ter" }, { location: "milwaukee", name: "baxter" }, { location: "sample", name: "sampename" } ]; Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond. arr.find(item => { if (item.location == "milwaukee" && item.name == "baxter") { barkTwice(); return true } });