How do you pass unknown amount of variables into a function in Javascript

Viewed 21

I am new to programming, as far as I know, we can pass variables into a function, let's say I can calculate the total price of a product by multiply the quantity and unit price.

const calculatePrice =(quantity,unitPrice)=>{
  let totalPrice=quantity*unitPrice;
  console.log(totalPrice)
  return totalPrice;
}

so I can use the above function to calculate the the total price by doing calculatePrice(2,3.5),so this will give me an answer of 7.

But what if I want to insert two items or three items (unsure amount)? for example,I want to get the the sum of 2*3.5 and 3*4.8 how do I implement this?

1 Answers

Functions are first class citizens in javascript, meaning your can use them where you'd use a variable. So, you can add their result as well.

var sumOfPrices = calculatePrice(2,3.5) + calculatePrice(3,4.8);
Related