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

Pushing new tokens to this.tokens

how about keeping the tokens array in the constructor as an empty array

this.tokens = []

and then pushing new tokens directly to this new array?

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

If I call the createTokens() method from elsewhere, would that work?

1 Answer

Simon Coates
Simon Coates
8,377 Points

There are probably a couple different ways to go about it. You could have the calling method pass in the array, i guess. You could have it act directly on this.tokens. Maybe there are some principles that dictate that particular code. Avoiding using this.token directly might make the code marginally more flexible if there is a 0.0001 chance that you'd ever want to create a different list of tokens. And maybe assignment makes the code more readable. To someone unfamiliar with the code, this.tokens = this.createTokens(21); is immediately very clear.