Mozarts
Mozarts

Reputation: 61

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

Upvotes: 1

Views: 43

Answers (2)

Tony Nguyen
Tony Nguyen

Reputation: 3488

A function without return keyword, it will automatically return undefined.

Why do you need to return cost?

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

In the function above how does js know what variable it need to return, so, if you want get cost variable value you need to return cost.

Upvotes: 0

brk
brk

Reputation: 50291

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.

Upvotes: 1

Related Questions