Search code examples
javascriptstringeloquentconcatenationchess

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);
}

Solution

  • 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);