Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  195] [ 7]  / answers: 1 / hits: 15641  / 9 Years ago, mon, october 5, 2015, 12:00:00

I didn't know this was possible (is it?)



The below code apparently logs values 1 to 5, then breaks out of the 'for' loop, because the 'false' value is returned.



function x() {
for (var i = 0; i < 10; i++) {
console.log(i);
if (i == 5) return false;
}
return true
}

console.log(x());


My question is:




  • How come the for loop short-circuits when 'false' is returned? I looked at MDN but there is nothing there about using 'false' to break out of the for loop. Also tried looking at ECMA specs, but sadly too noob.


  • Why doesn't the function return 'true' to the console, as the 'return true' statement exists after the 'for' loop is executed? Even if false somehow returns 'first', shouldn't 'true' return last or also?



More From » for-loop

 Answers
3

return false is not breaking your loop but returning control outside back.



function x() {
for (var i = 0; i < 10; i++) {
console.log(i);
if (i == 5) return false;
}
return true
}

console.log(x())


Output:



0
1
2
3
4
5
false //here returning false and control also


Where break will break your loop instead of coming out from function.



function x() {
for (var i = 0; i < 10; i++) {
console.log(i);
if (i == 5) break;
}
return true
}

console.log(x())


Will output:



0
1
2
3
4
5 //after this loop is breaking and ouputing true
true

[#64844] Thursday, October 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;