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 trialAgustin Vargas
10,896 PointsGlobal counter var
I think a more intuitive way of making unique ids would be to use:
this.state.players.push({
name: name,
score: 0,
id: (this.state.players.length + 1)
});
That way there's no need to pollute the global namespace.
Just my two cents.
2 Answers
Stan Day
36,802 PointsI agree, or even just assigning the counter variable on this.nextId would be preferable to the global variable.
Umesh Ravji
42,386 PointsHi Agustin, while I do agree that there would be better ways to assign unique ids, I'm sure it was just to keep things simple in this case. I don't think using the length of the players array would work, as it could result in numbers being reused for ids.
const players = [];
players.push(players.length); // 0
players.push(players.length); // 1
players.push(players.length); // 2
players.splice(1, 1);
players.push(players.length); // 2
console.log(players); // [0, 2, 2]
Agustin Vargas
10,896 PointsYou're right Umesh Ravji. In that case, Stanley E. M. Day's solution would suffice.