Trying to loop with a simple for loop and return the operation with a console.log

Viewed 37

Been trying to loop through this arr array and return the operation result, I know I'm missing something I just don't remember what. it is returning the array, not the operation. (i'm having a lot of problems with loop so please be patient).

let arr = [225, 555, 44];

// const calcTip = (bill) => bill > 50 && bill < 300 ? bill * 0.15 : bill * 0.20;

function calcTip(bill) {
    for (let index = 0; index < bill.length; index++) {
       if (bill[index] > 50 && bill[index] < 300) {
         bill[index] * 0.15;
       } else if (bill[index] < 50 && bill[index] > 300) {
         bill[index] * 0.20;
       }
    }
};
tip = calcTip (arr);
console.log(tip);

2 Answers

You are not changing the tip value (i assume that is what you are trying to do). You should create a tip array (so you have a tip for each bill) and pass it to the function and then:

tip[index] = bill[index] * 0.15;

First of all, there is a mistake in your boolean check

else if (bill[index] < 50 && bill[index] > 300)

It can't be less than 50 and greater than 300 at the same time. Either replace && with || or just use else instead - going from your ternary comment, this is probably what you wanted to have.

Second problem is that if you expect a return value out of the function, it will not work since you're not returning anything.

That said, the array is being changed in place, so could just replace

tip = calcTip (arr);
console.log(tip);

With

calcTip(arr);
console.log(arr);

If you do need a new array, just use .map

const tips = arr.map((amount) => amount > 50 && amount < 300 ? amount * 0.15 : amount * 0.2)
Related