Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript returning question

So im trying to build a tic tac toe game in javascript. Ive made a function that returns true if any of the winning combinations textContent is the same as the string "X" or "O". Now im pretty sure the function works fine. But at the bottom im trying to test the function. I want it to log "it works" to the console if any of the winning combinations are filled. But when i fill a winning combination in the table, nothing happens. Can someone explain why?

function checkWin(letter) {
    if (table[0] === letter && table[1] === letter && table[2] === letter) {
        return true
    } else if (table[3].textContent === letter && table[4].textContent === letter && table[5].textContent === letter) {
        return true
    } else if (table[6].textContent === letter && table[7].textContent === letter && table[8].textContent === letter) {
        return true
    } else if (table[0].textContent === letter && table[3].textContent === letter && table[6].textContent === letter) {
        return true
    } else if (table[1].textContent === letter && table[4].textContent === letter && table[7].textContent === letter) {
        return true
    } else if (table[2].textContent === letter && table[5].textContent === letter && table[8].textContent === letter) {
        return true
    } else if (table[0].textContent === letter && table[4].textContent === letter && table[8].textContent === letter) {
        return true
    } else if (table[6].textContent === letter && table[4].textContent === letter && table[2].textContent === letter) {
        return true
    }
}
const table = document.querySelectorAll(".table");
// Im pretty sure this is where im going wrong:
if (checkWin("X") === true) {
    console.log("it works!")
}

1 Answer

Steven Parker
Steven Parker
243,199 Points

It works for me, but I had to guess at the HTML. I created a table with 3 rows, each row had 3 td's, and each td had the classname of "table". Is your table like that?

If that's what you had already, or if this doesn't lead you to the issue, try posting your HTML also to allow a complete analysis.