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

Chris Shaffer
Chris Shaffer
12,030 Points

The for loop should probably use <= not < num.

If the goal is to create 21 tokens, not 20 tokens, then the for loop should use <= num (which is passed in when called as a value of 21).

The suggested solution is as follows:

class Player {
  constructor(name, id, color, active = false) {
    this.name = name;
    this.id = id;
    this.color = color;
    this.active = active // boolean - players turn
    this.tokens = createTokens(21) // create method to manage tokens
  }

  createTokens(num) {
    const tokens = []

    for (let i = 0; i < num; i++) {
      let token = new Token(i, this);
      tokens.push(token);
    }

    return tokens;
  }
}

It's not clear at this point in the if 21 or 20 is the intention, but if 21 is intended, this code will return 20 instead, and so is incorrect.

1 Answer

Seth Kroger
Seth Kroger
56,414 Points

< is correct here because the for loop starts at 0, not 1. It will create tokens from 0 to 20 which would be 21 in a zero-indexed array.

Chris Shaffer
Chris Shaffer
12,030 Points

Oh, duh, I know this! Long day. Thanks man.