Not able to iterate over an array, calculate and push the product in a new array

var bill = [300, 124, 48, 268]
function tipCal (arr) {
    var tip=[];
 for (var i = arr.length -1; i > 0; i--){
    if (arr[i] < 50){
        tip.push = arr[i] * .20
        i--
    } else if(arr[i]>= 50 && arr[i]< 200){
        tip.push = arr[i] * .15
        i--
    } else {
        tip.push = arr[i] * .1
        i--
    } return tip
}
}

Hav you seen the Free Code Camp section on push: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push

I have tried to modify my code , however the result of the same is [30] it is not iterating over each item of the array. Please review and suggest!

var bill = [300, 124, 48, 268]
function tipCal (arr) {
var tip=;
for (var i = 0; i < arr.length; i++){
if (arr[i] < 50){
tip.push(arr[i] * .20)
} else if(arr[i]>= 50 && arr[i]< 200){
tip.push(arr[i] * .15)
} else {
tip.push(arr[i] * .1)
} return tip
}
}
console.log (tipCal(bill))

You have a return inside your loop. As soon as you return you exit the function and stop iterating through the array. You’ll get the result you’re expecting if you move your return outside of the loop.

ProTip: To make your code show up correctly, put these symbols ``` on a new line before and after your block of code.

var bill = [300, 124, 48, 268]

function tipCal (arr) {
var tip= [];
for (var i = 0; i < arr.length; i++){
     if (arr[i] < 50){
         tip.push(arr[i] * .20)
     } 
    else if(arr[i]>= 50 && arr[i]< 200){
         tip.push(arr[i] * .15)
    } else {
       tip.push(arr[i] * .1)
    }
     return tip // you are returning in the loop. The loop will  run once
 }
// This is where you should return the tip array
}
console.log (tipCal(bill))

I have formatted your code for easy readability. Take the return statement outside the loop as commented.

Thanks Nibble, I understood the mistake I was making!

Thanks for the tip JeremyLT and providing an explanation.
I am very grateful!!

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it 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.

Note: Backticks are not single quotes.

markdown_Forums

Hi Ieahleen, Thanks for the tip, this was first post and was not aware of how I was suppose to do it. JermyTL has also suggested the same and I have taken a note of the same thanks again.

1 Like