Why isn't this string concatenating on one line? I am not "\n" breaking the line, shouldn't it log to the console like " # # # #"?
for (var i = 1; i <= 8; i++) {
var str = "";
if (i % 2 == 0)
str += "#";
else
str += " ";
console.log(str);
}
It's console.log function. It logs result of your expression on single line. Your code works like this: you just log ' ', than #, than ' ' and so on. If you want # # # #, you should not overwrite str on every iteration, but make one string with all values. Use this:
var str = "";
for (var i = 1; i <= 8; i++) {
if (i % 2 == 0) {
str += "#";
} else {
str += " ";
}
}
console.log(str);
Take a look at what's happening inside your for loop:
for (var i = 1; i <= 8; i++) {
var str = ""; // set `str` to an empty string
if (i % 2 == 0) // append "#" or " " to `str`
str += "#";
else
str += " ";
console.log(str); // write `str` the console
}
Everything between { and } will happen eight times, so you're creating an empty string eight times and you're calling console.log eight times.
If you want to create an empty string one time, append "#" or " " to it eight times, and then call console.log one time, you need to do some of those things outside of your for loop:
var str = "";
for (var i = 1; i <= 8; i++) {
if (i % 2 == 0) {
str += "#";
} else {
str += " ";
}
}
console.log(str);
// => # # # #
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With