Return


#1

Hello,

I have worked through the pizza example and I am not sure about the return exercise. Specifically I do not understand the:
function getSubTotal(itemCount){
return itemCount * 7.5;
}

console.log(getSubTotal(orderCount));

I am not following where “itemCount” comes from and how it is recognized in the final console line. Is “itemCount” just a placeholder for when you want to use “orderCount”. Could the getSubTotal have been written as getSubTotal(orderCount) return orderCount * 7.5?

  1. On the last line of your program, after the takeOrder function calls, call the getSubTotal function inside a console.log statement.

getSubTotal has a parameter that represents the amount of items ordered. Pass in the orderCount as an argument when making the function call.

My Code (it worked):
var orderCount = 0;

function takeOrder(topping, crustType) {
orderCount = orderCount + 1;

console.log('Order: ’ + crustType + ’ crust topped with ’ + topping);

}

takeOrder(‘bacon’, ‘thin’);
takeOrder(‘pepperoni’, ‘regular’);
takeOrder(‘pesto’, ‘thin’);
console.log(orderCount);

function getSubTotal(itemCount){
return itemCount * 7.5;
}

console.log(getSubTotal(orderCount));


#2

itemCount is a local variable that holds whatever value we submit to the function in the argument. It cannot be seen from the outside, and neither can any of the computation we do with it in the function. That is where return comes in… It lets us pass back the value resulting from the calculation, and not the variable itself.

We could just use the global variable, orderCount and not have any parameter, and when that variable is being modified by our function and nothing else, no return statement either. However this is not a good practice in the real world. Global variables are vulnerable and can collide with other programs running in the same namespace as ours.

Eg.

function getSubTotal(){
    return orderCount * 7.5;
}

Notice, no parameter. The call would be,

let subTotal = getSubTotal();

As it is now, we pass the orderCount value to the function and store it in itemCount, with which we complete our computation and return that value.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.