Search code examples
javascriptfunctionreturn

why do I need to put a return statement right before a function ends?


function getPizzaCost(size, nTopping) {
  let cost = 10; // base cost for a small pizza
  if(size === "medium") {cost += 4;}
  else if(size === "large") {cost += 8;}
  cost += nTopping;
}

let pizzaSize = "medium";
let numToppings = 19;

let cost = getPizzaCost(pizzaSize, numToppings);
console.log("cost " + cost + "$")

I know I'm supposed to put a return cost right below the cost += nToppings but why do I need to do that? is there a specific reason for that? I've search up why we needed it but it got a little confusing


Solution

  • That is because cost is a local variable to that function and the value of it is not accessible from outside. So the return statements gives back the value of cost once the function is executed.

    You can also declare it outside and use that , but that variable will be avaialble to be used by other function which will give an erroneous result.