21 Day Coding Challenge

Using 'break;' in code question/discussion


I have gone through a Computer Science degree program and I was always taught that there are better ways to break out of a loop than using the break command. Logically speaking, it should be better to have your code exit through returning a value or accomplishing something rather than ‘breaking’ away from the code. There are instances (switch statements) where breaks are necessary, but the fewer break commands the easier your code can be read.

It seems like there are others here that have experience with programming and I was curious if there are other opinions on this? I thought maybe since this challenge was geared at people with varying experience with JavaScript they would include an easy way to break from the code (such as the case with challenge 13), but I was curious what others have learned, been taught, or felt about this topic.

1 Like
Alternative answer to Challenge #13?

It felt odd to read to use “break”. I would understand in a While loop, but not in a For.

I thought of using Return instead since we’re inside a function and I got the value I wanted.


It’s possible that a break-statement is unnecessary. If you’re looking for a more elegant or ‘practical’ solution which does not change the overall runtime, I would encourage you to look at trying this challenge functionally (map-reduce style). Breaks are really just a construct to give the instruction that we don’t want to search further. However, I would caution on using early return statements. You should always try to keep your functions unary with only a single return statement


You should still be able to avoid using a break statement in a while loop. I was thinking with you that a break statement shouldn’t be used in a for loop, but I essentially did that with the while loop setting the index variable outside the range it was checking.


I figured that the case with challenge 13 was to prove your point that you can exit your loops early instead of going through each test case. I will have to look at the map-reduce style more, thanks!


I agree that breaking out of loop is frowned upon. The functional map/reduce approach is usually the way to go in these cases. However, it is possible to construct a loop that works without a break:

let i = 0;
let checks = 12;
let signal;
  signal = checkSignal();
  if(signal !== undefined) navigation.x = signal;
}while(i <= checks && signal === undefined);

Or you can return inside the for loop, instead of having a break;