Return - Help with understanding


#1

https://www.codecademy.com/courses/learn-javascript/lessons/functions/exercises/return?action=lesson_resume

My code isn't behaving incorrectly. I just need an explanation for how and why this works. How does the computer know how many pizzas I ordered when the two functions aren't directly related to each other?

Thanks in advance!


var orderCount = 0;

function takeOrder(topping, crustType){
  console.log('Order: '+ crustType +' crust pizza that is topped with ' + topping);
  orderCount = orderCount + 1;
}

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

takeOrder('chicken', 'stuffed');
takeOrder('bacon', 'grilled cheese');
takeOrder('spinach', 'thin');

console.log(getSubTotal(orderCount));


#2

Looking through, I think this answers your question...

Your first function will in addition to logging what's being ordered, will add 1 to the orderCount variable. So, when you write the getSubTotal function with itemCount as the parameter, it should return itemCount*7.5. So...

When you call console.log(getSubTotal(orderCount)); you are running the function getSubTotal and TAKING the variable orderCount as the parameter. So whatever takeOrder makes orderCount, is what the getSubTotal uses for itemCount.

A little bit of a confusing explanation, so here's the simplified explanation:

takeOrder changes orderCount and getSubTotal takes orderCount as a parameter, so the actions taken by takeOrder on orderCount affect the result of getSubTotal.

Hope this helps, feel free to respond if you need it cleared up any further.


#3

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