Reputation: 22113
I am a little confused about the logics of while loop
. Suppose such a minimal code:
var i = 1; // Set counter to 1
var msg = ''; // Message
// Store 5 times table in a variable
while (i < 10) {
msg += i + ' x 5 = ' + (i * 5) + "\n";
i++;
}
console.log(msg) // the console is placed out of {}
Run it and come by:
1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45
I guessed it would just output:
9 x 5 = 45
Because, the while loop stops on i = 9, and console.log(msg)
is implemented after while loop finished since it is not within {},
However, the result is beyond my expectation. How to understand it?
Upvotes: 1
Views: 94
Reputation: 21766
You msg
is getting printed ONLY once but you are appending your each result to msg
string in a formatted way i.e adding /n
as well so that next result will print in new line.
So if you want to print only 9 x 5 = 45
then use below code:
msg = i + ' x 5 = ' + (i * 5) + "\n";
Demo below:
var i = 1; // Set counter to 1
var msg = ''; // Message
// Store 5 times table in a variable
while (i < 10) {
msg = i + ' x 5 = ' + (i * 5) + "\n";
i++;
}
console.log(msg) // the console is placed out of {}
If you want to print complete table then keep it as it is:
msg += i + ' x 5 = ' + (i * 5) + "\n";
Demo below:
var i = 1; // Set counter to 1
var msg = ''; // Message
// Store 5 times table in a variable
while (i < 10) {
msg += i + ' x 5 = ' + (i * 5) + "\n";
i++;
}
console.log(msg) // the console is placed out of {}
Upvotes: 1
Reputation: 1313
msg += i + ' x 5 = ' + (i * 5) + "\n";
That line runs for every number and you are appending to string. The string kept on taking each line for 1-9 and finally when you did console.log, it dropped the whole string. Put a console.log inside while to see the string increasing in every loop. like 1, then 1,2 then 1,2,3 and so on.
Upvotes: 3