Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation - eloquent javascript chess board

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);
}
like image 399
slurrr Avatar asked Jun 24 '26 01:06

slurrr


2 Answers

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);
like image 177
Ivan Avatar answered Jun 25 '26 14:06

Ivan


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);
// => # # # # 
like image 27
Jordan Running Avatar answered Jun 25 '26 14:06

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!