About chapter's 2 third exercise, thechess exercise, from Eloquent javascript

Hello,
i have a question, why this code shows the chess pattern asked in the thrid exercise of second chapter of Eloquent JavaScript

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

but it shows me not a chess pattern if i change console.log(board) to document.write(board), instead it throws all in one line, seems that “\n” isn’t working here. Why is that change between console and body of html page? and why “\n” do not make a new line when its showed in the html page, and when its printed in console it does work printing new line?
I’m asking because everyother exercise that i made i changed console.log for document.write and it worked fine. Thanks.
I also changed board += "\n" to board += "<br>" and it makes the line change/break, but starts every line with # and ends with space, so no chess pattern still :sweat_smile:

The document object represents an HTML document; any text written to the document will be processed by the browser’s HTML renderer. In HTML, all adjacent whitespace are collapsed into a single space when rendered. You can make \n work by writing into a <pre> element:

<html>
  <body>
    <pre>
    <script type="text/javascript">
      let size = 8;
      let board = "";
      for (let y = 0; y < size; y++) {
          for (let x = 0; x < size; x++){
                 if ( (y + x) % 2 == 0) {
                       board += " ";
                  }else {
                      board += "#";
                  }
           }
            board += "\n";
     }
    document.write(board)
    </script>
    </pre>
  </body>
</html>
1 Like