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

Marcell Ciszek
Marcell Ciszek
7,255 Points

square brackets, why?

    playToken() {
        let spacec = this.board.spaces;
        let activeToken = this.spaces[activePlayer.activeToken];
        let targetSpace = null


        for (let token of this.column ){
            if ( token !== column) {
                game = false
            }
        }
    }

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Marcell Ciszek,

Square brackets denote a key selection within an object. In the example you have given above, you are using the activeToken property on the activePlayer object to find a position within the this.spaces array.

The same syntax can too be used for objects and strings alike since they all inherit the same behaviour. E.g.

const foo = 'bar'[1] // yields "a"
const bar = { foo: 'Hello', bar: 'World' }['foo'] // yields "Hello"

Hope that helps!

Zack Jackson
Zack Jackson
30,220 Points

It's selecting the index of the spaces array using activePlayer.activeToken as the index. It's hard to see in your code when the activePlayer.activeToken is not returning a value for you to see. Try console logging it.

Here's a simplified example of what your code is setup to do:

spaces = [ "a", "b", "c" ];
return spaces[0];

"a"

OR

return spaces[2];

"c"