Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFrank Greek
Full Stack JavaScript Techdegree Student 981 PointsReturn
function counter() {
for (let count = 1; ; count++) { // infinite loop
console.log(`${count}A`); // until 5
if (count === 5) {
return;
}
console.log(`${count}B`); // until 4
}
console.log(`${count}C`); // never appears
}
counter();
// Logs:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
Why this code runs for B only until 4 and never appear for C
1 Answer
Mark Sebeck
Treehouse Moderator 37,905 PointsHi Frank. Because of your if statement. You have the If after you print A. So when count === 5 it will first print 5A then the if statement will be true and it will return. Return exits the function and returns control back to the calling program. Since you have no more program it ends. If you change to a break statement you would break out of the for statement and print 5C after 5A then return.
Hope this helps Frank. Good luck