# [SOLVED] Javascript for loop function not working in another function

## Issue

The function "reversedcurrConvert", which contains a for loop and which is called in function checkCashRegister, is working only from index 1 onwards. Curiously it does not work for index 0 which is cid. Can’t wrap my head around what could’ve caused this behaviour.

``````function reversedcurrConvert(cid) {
for (let i = 0; i < cid.length; i++) {
if (i = 0) {
cid[i] = "PENNY"
}
if (i = 1) {
cid[i] = "NICKEL"
}
if (i = 2) {
cid[i] = "DIME"
}
if (i = 3) {
cid[i] = "QUARTER"
}
if (i = 4) {
cid[i] = "ONE"
}
if (i = 5) {
cid[i] = "FIVE"
}
if (i = 6) {
cid[i] = "TEN"
}
if (i = 7) {
cid[i] = "TWENTY"
}
if (i = 8) {
cid[i] = "ONE HUNDRED"
}
}
return cid
}

function checkCashRegister(price, cash, cid) {
let change = {}

cid = 0.01;
cid = 0.05;
cid = 0.1;
cid = 0.25;
cid = 1;
cid = 5;
cid = 10;
cid = 20;
cid = 100;

change['status'] = "CLOSED"
change['change'] = reversedcurrConvert(cid)
return change

}

console.log(checkCashRegister(19.5, 20, [
["PENNY", 0.5],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
]));``````

## Solution

The first problem that you must use `i == x` in your loop instead of `i = x`. The second problem you do a lot of unnecessary `if`. Here is example how you can easily set the value by using object as map

``````function reversedcurrConvert(cid) {
const banknoteName = {
0: 'PENNY',
1: 'NICKEL',
2: 'DIME',
3: 'QUARTER',
4: 'ONE',
5: 'FIVE',
6: 'TEN',
7: 'TWENTY',
8: 'ONE HUNDRED',
};

for (let i = 0; i < cid.length; ++i) {
cid[i] = banknoteName[i];
}

return cid;
}

function checkCashRegister(price, cash, cid) {
let change = {}

cid = 0.01;
cid = 0.05;
cid = 0.1;
cid = 0.25;
cid = 1;
cid = 5;
cid = 10;
cid = 20;
cid = 100;

change['status'] = 'CLOSED';
change['change'] = reversedcurrConvert(cid);

return change
}

console.log(checkCashRegister(19.5, 20, [
["PENNY", 0.5],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
]));``````

P.S. I really didn’t clearly understand why you at first time set numbers into `cid[x]` and then set `string` with `for` loop. When you pass `cid` into `reversedcurrConvert` function you pass pointer to this array not it’s copy, if you don’t know. Because of it when you change value in your `reversedcurrConvert` function you also change values of `cid` in `checkCashRegister` function. So you can set this strings without looping as you do it before calling `reversedcurrConvert` function

Answered By – EzioMercer

Answer Checked By – Gilberto Lyons (BugsFixing Admin)