a question regarding loops in javascript

why is that when we create a loop for example let friendsInTheOffice = 0; while(friendsInTheOffice < 10) { console.log(friendsInTheOffice) // if we.console log here we get the result 9 friendsInTheOffice++ } console.log(friendsInTheOffice) // however if we console.log here we get the result 10 if someone can provide me with a in-depth explonation i'd really appreciate it, a.k.a i am new at learning JavaScript.
3 Replies
Jochem
Jochem3mo ago
Try to get into the habbit of formatting and indenting your code properly, it'll save you a lot of frustration later. And be consistent with your semicolon use.
let friendsInTheOffice = 0;

while(friendsInTheOffice < 10) {
console.log(friendsInTheOffice);
friendsInTheOffice++;
}

console.log(friendsInTheOffice);
let friendsInTheOffice = 0;

while(friendsInTheOffice < 10) {
console.log(friendsInTheOffice);
friendsInTheOffice++;
}

console.log(friendsInTheOffice);
When the while evaluates, if the condition is false, it doesn't execute the code in the block at all. So when the console.log in the while block runs and prints 9, the next line then updates the variable to 10, which means the block won't run again to show you 10. The variable did get updated though, so when you run the console log after the loop, it will show 10 because that's what the value is, and what the value needs to be (at least) to exit out of the loop
ἔρως
ἔρως3mo ago
if you want to change it to show the numbers from 0 to 10, you need to use the <= (lower or equal) symbol instead of < if you want from 1 to 10, you can just move friendsInTheOffice++; to before the console.log
theboyduddus
theboyduddusOP3mo ago
good explonations, thank you.
Want results from more Discord servers?
Add your server