I would consider building the board as a separate concern from displaying the board. I say this as it is more practical from a learning standpoint to understand how you might build the data structure that represents a chessboard (for example a two-dimensional array) not, just how to display it by building a string. During your programming journey, you will likely learn to embrace the separation of logic/data storage concerns from display concerns.
I would also encourage you to more heavily leverage Array()
functions.
function buildBoard(size) {
var board = Array(size);
for (var row = 0; row < size; row++) {
board[row] = Array(size).fill(0);
for (var col = row % 2; col < size; col = col + 2) {
board[row][col] = 1;
}
}
return board;
}
function displayBoard(size) {
var board = buildBoard(size);
var output = '';
board.forEach(function(row) {
row.forEach(function(col) {
output += (col === 1) ? '#' : ' ';
});
output += "\n";
});
console.log(output);
}
displayBoard(8);
This might yield something like:
function buildBoard(size) {
var board = Array(size);
for (var row = 0; row < size; row++) {
board[row] = Array(size).fill(0);
for (var col = row % 2; col < size; col = col + 2) {
board[row][col] = 1;
}
}
return board;
}
function displayBoard(size) {
var board = buildBoard(size);
var output = '';
board.forEach(function(row) {
row.forEach(function(col) {
output += (col === 1) ? '#' : ' ';
});
output += "\n";
});
console.log(output);
}
displayBoard(8);
displayBoard(20);
Now this certainly is not optimized from the standpoint of of operational complexity (in that you have to perform \$O(n^2)\$ iteration twice, but it does break down the problem into the logic space of setting up a board and then displaying a board, which has more real-world applicability than building a chessboard directly into a string.