Exact Change - Cannot Read Property '1' of Undefined Bug

Exact Change - Cannot Read Property '1' of Undefined Bug
0.0 0

#1

Hi there campers,

Could someone help me understand why I am getting a “Cannot Read Property ‘1’ of Undefined” message when I try to run my code? The problem occurs the first line inside the While Loop. Thanks in advance!

function checkCashRegister(price, cash, cid) {
  let change = [],
      changeArray = [100, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01],
      changeDue = (cash-price).toFixed(2),
      totalCID = 0,
      i = 8;
 cid.forEach(function(money) {
    totalCID += money[1];
  });
  totalCID = totalCID.toFixed(2);
  if (price > cash) {
    return "Not Enough Cash";
  }
  else if (totalCID < changeDue) {
    return "Insufficient Funds";
  }
  else if (totalCID == changeDue) {
    return "Closed";
  }
  while (changeDue !== 0) {
    if (changeDue >= cid[i][1]) {
      changeDue -= cid[i][1];
      change.push(cid[i]);
      i--;
    }
    else if (changeDue < cid[i][1] && changeDue > changeArray[i]) {
      changeDue = changeDue - Math.round(changeDue/changeArray[i]);
      cid[i][1] = changeArray[i] * (Math.round(changeDue/changeArray[i]));
      change.push(cid[i]);
      i--;
    }
    else {
      i--;
    }
  }
  return change;
}

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Put the following console.log statement in and you will see why.

  while (changeDue !== 0) {
    console.log(i, cid[i]);  // added to see the value of i and cid[i] at each iteration
    if (changeDue >= cid[i][1]) {

#4

thanks for your help Randell