ratavagn
ratavagn

Reputation: 77

Why this function returns cannot read undefined variable while the variable is actually defined?

This is the function:

function exchangeScore(players) {
  for (let i = 0; i < listItem.length; i++) {
    for (let j = 0; j < listItem.length - i - 1; j++) {
      if (listItem[j].harga < listItem[j + 1].harga) {
        var tmp = listItem[j]
        listItem[j] = listItem[j + 1]
        listItem[j + 1] = tmp
      }
    }
  }

  let output = []
  for (let i = 0; i < players.length; i++) {
    let person = {}
    person.name = players[i].name
    person.items = []
    person.points = players[i].points
    output.push(person)
  }


  for (let i = 0; i < output.length; i++) {
    var k = 0
    while (output[i].points > 0 && listItem[k].stock > 0) {
      if (output[i].points >= listItem[k].harga && listItem[k].stock > 0) {
        output[i].items.push(listItem[k].name)
        listItem[k].stock--
          output[i].points -= listItem[k].harga
      }
      k++
    }
  }
  return output
}

let listItem = [
  {name: "Teddy Bear", harga: 1000, stock:1},
  {name: "Toy Soldier", harga: 200, stock: 5},
  {name: "Ducky", harga: 500, stock: 3},
  {name: "Bunny", harga: 300, stock: 2},
  {name: "Buzz Lightyear", harga: 2000, stock: 1}]

console.log(exchangeScore([
   {name: "Yanto Kopling", points:100}, 
   {name: "Audric", points: 300}, 
   {name: "Ayu", points: 1000}, 
   {name: "Semmi", points:1000}, 
   {name: "Mahdi", points: 2000}, 
   {name: "Sofyan", points: 2000}
 ]));

The function keeps returning "TypeError: Cannot read property 'stock' of undefined at exchangeScore (/home/runner/MotherlyYummyTest/index.js:31:45)" while I think I have define all variables. Do you have any idea about this problem?

Upvotes: 0

Views: 66

Answers (1)

Abhilash S S
Abhilash S S

Reputation: 102

You need to change the while loop

while (output[i].points > 0 && listItem[k] && listItem[k].stock > 0)

In your code k is incrementing every time in the while loop. At k = 5, there is no element in listItem[5] position. So it will give the error`

listItem[k] is undefined

So before checking listItem[k].stock > 0, you need to check there is anything.

Upvotes: 2

Related Questions