Home > Software engineering >  How to create a function which multiply the quantity of the product to the cost and add to the total
How to create a function which multiply the quantity of the product to the cost and add to the total

Time:10-09

Let's say I have 10 bottles of water with the price of 0,8cent for each one, I need to find the total cost of 10 bottles so I multiply 10 by 0,8 which makes 8,00$. Next I need to find 18% of 8$ and add it to 8$. I wrote some code but it shows that the result is not a function:

function multyAll(quantity, oneCost) {
 quantity = prompt('Insert quantity')
 oneCost = prompt('Insert the cost')
let mul = quantity * oneCost;
function totalPer() {
    let percent = (mul * 18) / 100
return percent
}
return mul
}
let result = multyAll(12, 0.8)
console.log(result())

CodePudding user response:

I'm not sure why you're trying to reassign your parameters in your function, since they're what's passed to it for your values. Your error message "result is not a function" is because you're console logging result() (the parentheses mean you want to run the function, but result isn't a function, it's the result of a function). I believe this code should solve your problems

function calculatePrice(quantity, unitPrice, taxRate){
    const subtotal = quantity * unitPrice;
    const total = subtotal   (subtotal * taxRate);
    return total;
}

console.log(calculatePrice(10, .8, .18)); // outputs $9.44

This function takes 10 units (bottles of water) and multiplies them by their unit price ($.80), and adds the amount in tax to that result (you said 18%).

CodePudding user response:

you wrote console.log(result()) in last line, should be console.log(result) without parentheses after result. You getting result is not a function because resoult is variable and adding parathesis after it javascript angine wants to invoke it as function.

  • Related