Just a quick question with values that are being printed


#1

Hello, I'm just wondering about the values being printed on the console in some of the programs I've been doing in JS through these exercises. My code is working fine, I am just wondering why, with the example code below, after printing out 5 "Bla!" and 5 "Bla" the console prints out "1"? The same thing happens with some of the while loops when the console prints out "false" at the end of program without ever writing a command to do so. Is this some CodeAcademy helping system or is this a thing in JS and if so, how do I avoid it?

Thanks in advance!

var number = 5;

for(i = number; i>0; i--)
    console.log("Bla!");
    
while(number){
    console.log("Bla");
    number--;}


#2

this is console behavior, it logs the value of number, you can simply avoid this by decreasing number before logging:

number--;
console.log("Bla");

Now, now variable is changed after the last console.log() so the console won't log number to the console


#3

Thanks! It works and now I understand that little bit of console behavior.

I also realised that I would've compromised the for loop with these conditions if the while loop came before the for loop in the code, because the number--; changes the number value on a global scale, so I will use a function or a substitute variable in the future.


#4

Glad i could help. Yea, be aware of variable scope.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.