Practice makes perfect #5


I was messing around with the code and I am wondering why this code prints the following result.

var count = 0

while(count < 3){
console.log("I'm looping!");


I'm looping
I'm looping
I'm looping

what's with the number 2? where did it come from ?



That was the number that "count" ended on that doesn't allow the while loop to continue any longer. This is part of using the "console.log();" statement, as "console.log();" is just a debug tool for programmers. I'm assuming though that your lesson still passed and you're able to continue? In this case you didn't make a mistake using the code you used.


yes it did pass. I actually used a similar code later on and that random number did not appear. Nice to know I'm not crazy! thanks @lolman


That's actually a "feature" of the console. If you enter any value in it you get the value echoed back on you e.g. enter 2+2 and you see 4 on the screen. For longer pieces of code only the last statements value is shown and only if it is not undefined. So what you see in your code is the value of count++ and if you really want to get rid of it you can switch console.log with count++ as console.log has no own value (aka undefined). So it's not a random output but actually the last value and it's nothing to worry about. Also as @lolman already mentioned it is part of the console (console.log is just one way to write to a console) which is a debugging tool so in real applications the console is not the primary output but a sidechannel where you can see how the code works without actually change a website and in this case it might be even good to get a quick response by tha last value.


this piece of code will solve your problem:
var count=0;

var loop = function(){
console.log("I'm looping!");



Why didn't you use a parameter for your function?


To me the wording trough me off.

("We actually know we need to loop three times, so we could use a for loop, but we'll use while this time.

If we create a variable called count and set it to 0 outside the loop (on line 2), then do count++ each time we console.log() inside the loop, we'll be able to track how many loops we've made. If we set the while condition to be count < 3, that should do the trick!")