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

252
Views
Why is this `while` loop not iterating and just exiting?
function aiPick() {
    let aiCell = null;
    while (aiCell == null) {
      let aiColIndex = Math.floor(Math.random() * 7)
      console.log(aiColIndex)
      aiCell = getFirstOpenCellForColumn(aiColIndex) 
      console.log(typeof(aiCell))
      console.log(getClassListArray(aiCell))
    }
    aiCell.classList.add('red')
    checkStatusOfGame(aiCell)
    yellowIsNext = !yellowIsNext
    aiClassList = getClassListArray(aiCell)
    aiColClass = aiClassList.find(className => className.includes('col'));
    let aiColIndex = parseInt(aiColClass[4], 10);
    clearColorFromTop(aiColIndex)
}

I'm working on an opponent for a Connect Four game. I'm having it pick one of seven columns by random, and then the function getFirstOpenCellForColumn will mark the first open cell by adding a class of red to that div.

The code then checks if the move is a win with checkStatusOfGame(aiCell) and swaps the player and removes a token that shows up at the top of the column, outside the gameboard, that serves as a "picker."

I was looking for a way to get the computer to generate a new random number to pick a column when the last space in the column was occupied. I thought this would do it, since when the computer picks a full column, it gives me this error message:

script.js:39 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at getClassListArray (script.js:39)
    at aiPick (script.js:274)
    at HTMLDivElement.handleCellClick (script.js:258)

But then it seems not to go back to picking a random number, but simply jumps down to yellowIsNext = !yellowIsNext so that I'm now placing the computer's red token instead of my yellow ones.

Basically, I want the code to

  1. pick a random number
  2. put the token in the column corresponding to that number
  3. if that column is full, go back to #1

Do you know why this isn't working? Is there another way to write the while loop, or is let aiCell = null incorrect?

Thanks!

about 4 years ago · Santiago Gelvez
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!