0

I have the following code:

let size = 8;
let board = "";

for (let y = 0; y < size; y++) {
  for (let x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }    
  }
  board += "\n";
}

console.log(board);
document.write(board);
<h1 style="text-align: center; color: rebeccapurple;">Chess Board</h1>

console.log output:

enter image description here

document.write output:

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

Why do they output different results?

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • 1
    `document.write` makes changes to the `DOM`, and doesn't recognize `\n` (a new line character in JS) as an HTML line break. You need to use `
    ` to see a line break in HTML
    – Anurag Srivastava Feb 13 '21 at 09:33
  • Btw, don't ever use `document.write`... Use `console.log` for debugging and `.textContent`, `.innerText`, or if you absolutely need to, `.innerHTML` to display text in the document. – FZs Feb 13 '21 at 09:41
  • 1
    If you want the browser to render whitespace as the occur in the source then use a `
    ` element or set the `white-space: pre;` CSS property.
    – Felix Kling Feb 13 '21 at 09:47

1 Answers1

0

the Document interprets html. " " and "\n" is not HTML code. You should use "&nbsp;" and "<br/>" instead of " " and "\n"

for (let y = 0; y < size; y++) {
  for (let x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += "&nbsp;";
    } else {
      board += "#";
    }    
  }
  board += "<br/>";
}
Hasan Genc
  • 33
  • 1
  • 6