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

Juan Francisco Andrade Álvarez
Juan Francisco Andrade Álvarez
23,997 Points

Pushing a token into the tokens array

Is it possible to change the way of adding a token to the array of tokens like this?:

createTokens(number) {
    let tokens = [];
    for (let i = 0; i < number; i++) {
      let token = new Token(i, this);
      tokens[i] = token;
    }
    return tokens;
  }

1 Answer

Steven Parker
Steven Parker
231,275 Points

Sure, that does exactly the same thing as the course example. The difference in using "push" is that it always adds to the end so you don't need to keep track of the index.

Also, you can still use "const" since "tokens" is never re-assigned, only indexed.

Juan Francisco Andrade Álvarez
Juan Francisco Andrade Álvarez
23,997 Points

But in this example the indexes don't need to be tracked, do they?

Steven Parker
Steven Parker
231,275 Points

No, they don't. That's why "push" is a good choice in this situation.