-1

Im teaching myself jS and hoping someone could explain why currentPlayer is undefined.

Is it something that jS doesn't support or am I doing it wrong?

the array gets filled in a function later in the code and turnCount increments

let playersArr = [];
let turnCount = 0;
const currentPlayer = playersArr[turnCount];

any insights would be appreciated.

  • 5
    `playerArr` is empty at the time you call `playersArr[turnCount]` so any index will return `undefined` – Phil Jun 30 '21 at 00:33
  • If you're expecting `currentPlayer` to _reference_ the array index even before it's defined, this might answer your question... [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Phil Jun 30 '21 at 00:35
  • "*I have `arr = []` Why `console.log(arr[4])` gives `undefined`?!*" That's exactly what you're asking. – Roko C. Buljan Jun 30 '21 at 00:47
  • Thanks, I appreciate the explanation. I'm assuming I can't create```currentPlayer``` in a function without it getting scoped. – imJusAskin Jun 30 '21 at 00:56
  • @imJusAskin it all depends, on after some `event` you can always get any value from your array - if it's been meanwhile populated with values (using `.push()` or any other way to populate arrays) – Roko C. Buljan Jun 30 '21 at 00:57

2 Answers2

0

I believe it returns undefined because you are accessing the variable before it is filled. What you could do is, move the code that fills the array up so that it is before when the array is accessed.

0
**playerCurrent is empty**
turnCount = 0, ergo playerCurrent[0] = undefined

try this:

playerCurrent = Object.entries(['one', 'two', 'three']);
for(i in playerCurrent) console.log(playerCurrent[i][1]);
user1269348
  • 65
  • 1
  • 5