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 Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects createTokens() Method Solution

Hard time understanding code

/**
 * Creates token objects for player
 * @param   {integer}   num - Number of token objects to be created
 * @return  {array}     tokens - an arary of new token objects
 */

createTokens(num)

 {

    const tokens = [];

    for (let i = 0; i < num; i++)

 {
        let token = new Token(i, this);

        tokens.push(token);

    }

    return tokens;

}

I am having hard time understanding code. Why we wrote and what does it do. If anyone can explain it is much appreciated.

Also, we passed 21 in the constructor. Then why do we require to write this method? Cant we split the tokens between players?

Félix Guérin Camilo Lucero

2 Answers

Akshay Alok
Akshay Alok
7,857 Points

This method is a behavior defined for the class "Player" in Player.js. What this does is that it creates an array with a number of "Token" objects for the player to play. When this method is called in the constructor it can be seen analogous to "giving the player" a set number of tokens (21 in this case).

So we can say that this method is used for making an array of Token objects and returning it to be assigned to the tokens property of a player. Calling it in the constructor just means that, by default players will get a token array with (21) tokens in it.

Steven Parker
Steven Parker
231,271 Points

The number passed to the constructor is not related to the players. It's just a count of how many tokens you want the function to create.

Okay. Can you also help me understand the above code?

Steven Parker
Steven Parker
231,271 Points

I"m not sure what part you may find confusing. I'll try to answer any specific questions you have about it.