Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

414
Views
Is there a better way to make a chessboard in Javascript?

Hey I am new to javascript. I have just started reading Eloquent Javascript by Marin Haverbeke and I finished the chessboard problem in chapter 2 but I was wondering if my solution is good enough. I tried making the chessboard with nested loops but I am not very familiar with Javascript so I decided to only use one loop. I believe it is a faster solution because it runs in O(n) time where n is the size of the n x n board.

const boardSize = 8;
for (let i = 0; i < boardSize / 2; i++) {
  console.log(" #".repeat(boardSize / 2));
  console.log("# ".repeat(boardSize / 2));
}

You can change the boardSize so it will work for any size board. Output looks something like this:

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

Please let me know if this is cheating or if it is an acceptable solution. All advice is apprenciated :)

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your solution is perfectly acceptable.

You could also aim to call console.log only once, and avoid even that remaining for loop:

const boardSize = 8;
const row = " #".repeat(boardSize / 2);
const doublerow = row + "\n" + row.slice(1) + " \n";
console.log(doublerow.repeat(boardSize / 2).slice(0, -1));

Unless boardsize could have any value, the time complexity is irrelevant. But if larger sizes are allowed, then your solution is still O(n²) since that is the amount of characters it outputs. Specifically, the repeat method does not run in constant time if the argument is variable.

about 4 years ago · Juan Pablo Isaza Report

0

A chessboard has 64 squares. How about only one console.log

const boardSize = 4;
const board = [];
for (let i = 0; i < boardSize; i++) {
  board.push("⬛⬜".repeat(boardSize));
  board.push("⬜⬛".repeat(boardSize));
}
console.log(board.join("\n"))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!