To expand on @Gintsm’s response… This is not really a problem of a “break” operation but rather this is pure misuse of syntax which some better coding habits and formatting would have avoided completely.
So, to explain a little BOTH for
and if
process exactly ONE statement if the condition is truthy. Note that an if...else
is a single statement as far as the compiler is concerned.
So, if you were to rewrite your code using {...}
's and including a little proper formatting and indentation you’d perhaps see your error. As such:
------Code 1------
const numbers =[1,2,3,4,5,6];
console.log (includes(numbers,5));
function includes (array, searchElement) {
for (key of array) {
if (key === searchElement) {
return true;
}
}
return false;
};
====> Console output is “true”
----Code 2----
const numbers =[1,2,3,4,5,6];
console.log (includes(numbers,5));
function includes (array, searchElement) {
for (key of array) {
if (key === searchElement) {
return true;
}
else {
return false;
}
}
};
=====> Console output is " false"
So again in Code 1 you can see that the return false;
actually occurs after ALL of the elements in the array are processed (i.e. it searches the entire array for the searchElement).
In Code 2 however the if…else get’s processed as a “block” and the else will return false for the very first element in the array (1 !== 5). In fact, that means that the function in Code 2 would better be called “isFirstElement” because it will ONLY check the first element of the array and then return true or false.
What you’ve encountered is the problem of NOT using {…}'s in your if and for (and elsewhere). These kinds of statements are VERY error prone and VERY hard to find/see (since your brain will easily ignore the problem and see what you intended instead of what you actually wrote). Hopefully by adding them (and properly indenting/formatting your code) you can more easily pick out the problem with this code.
I’ve mentored dozens of jr. programmers in my career and my #1 recommendation is to NEVER, NEVER skip the {…}'s as it makes the code clear and scopes the statement. Also in this way when you (or a different developer) return to this code 6 months later and add a second line of logic you don’t accidently mis-place it.