Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading