JavaScript React Basics (retired) Designing Data Flow Adding Players to the Scoreboard

Agustin Vargas
Agustin Vargas
10,896 Points

Global 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
Stan Day
36,662 Points

I agree, or even just assigning the counter variable on this.nextId would be preferable to the global variable.

Umesh Ravji
Umesh Ravji
42,357 Points

Hi 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
Agustin Vargas
10,896 Points

You're right Umesh Ravji. In that case, Stanley E. M. Day's solution would suffice.