Returns: Does placement of 'orderCount' matter?


#1

I noticed that if i place the orderCount above the return, the subtotal is correct, but if it is placed below the return, the subtotal shows ‘0’. Does the placement matter? If it does, what is the general rule for this placement?

Correct value : http://prntscr.com/g18stn
Wrong value: http://prntscr.com/g18t2n

Below is my codes which shows the correct subtotal.

var orderCount = 0;

function takeOrder (crustType, topping) {
orderCount = orderCount + 1
return ('Order: ’ + crustType + ’ topped with ’ + topping )
}

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

console.log (takeOrder (‘thin crust’, ‘bacon’));
console.log (takeOrder (‘thin crust’, ‘bacon’));
console.log (takeOrder (‘thin crust’, ‘bacon’));

console.log(getSubTotal(orderCount));


#2

orderCount must be defined before it is referenced, so the top of the code is place for it, or at least before any function calls.


#3

but I have already defined the orderCount variable before using it in the function.
var orderCount = 0;

how does the placement of orderCount in the function below matter?

function takeOrder (crustType, topping) {
orderCount = orderCount + 1
return ('Order: ’ + crustType + ’ topped with ’ + topping )
}

vs

function takeOrder (crustType, topping) {
return ('Order: ’ + crustType + ’ topped with ’ + topping )
orderCount = orderCount + 1
}

must return always be placed at the last line of the function?


#4

Ah, in that case it would need to be before the return. Anything after return is unreachable.


#5

Aight! I will keep that in mind next time!

Thanks much!!


#6

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