Can you help me figure out this For Loop exercise?

I’m trying to create a chessboard from the bottom of this Eloquent Java Script ebook page (Program Structure :: Eloquent JavaScript). Problem is I don’t see how I can change the patterns on each row of the chess board… I end up with this:

let chessBoard = "" for(let i = 0; i < 8; i++){ for(let j = 0; j < 8; j++){ if( j%2 === 0){ chessBoard = chessBoard + '#'; } else { chessBoard = chessBoard + ' '; } } chessBoard = chessBoard + '\n'; } console.log(chessBoard)

And I want the pattern to change from black, white… to white black on each different row…

Hi Luigi,
welcome to the forum!
You have to take into account the modulo of i, too.
Every other digit per line is a space, that works. But you want that pattern to continue after each line ends, right? So you just need to sum up i and j and then check if their modulo is 0.

1 Like

Thank you Mirja!
I had found another solution but it involved too many if statements and looked very bloated… intuitively this solution didn’t occur to me… I’m trying to build that sense up though. But yes, if I add both i and j on each iteration I get a continuous pattern!

1 Like