Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

General Discussion

For Loop, One Question

I understand the for loop and it's cool.....but i have one question: When i use this code->

for(var counter = 10;counter;counter = counter - 1) {
    console.log("Hello World");
}

console.log("After");

when i run this i get a "Hello World" in the console with a little "10" next to it. But when i add the value counter to the console .log :

for(var counter = 10;counter;counter = counter - 1) {
    console.log("Hello World", counter);
}

console.log("After");

it prints "Hello World" out ten times - i am wondering why??

2 Answers

Kenneth Camilleri
Kenneth Camilleri
7,816 Points

Ah. What's happening is that the log collapses output text that is exactly the same. The "10" next to the Hello World is the number of times the same text has been outputted consecutively. However, since in the second code the text is different every iteration, it doesn't group them into one console output line.

Nice, that makes since.....thanks alot!