0

I am a newbie to Javascript and I'm not sure why my code works. I learn through Codecademy and here is my code:

var orderCount = 0
function takeOrder(topping, crustType) {
  orderCount = orderCount + 1;
  console.log('Order: ' + crustType + ' pizza topped with ' + topping);
  console.log(getSubTotal(orderCount));
}
function getSubTotal(itemCount) {
  return itemCount * 7.5
}
takeOrder('peperoni', 'thin');
takeOrder('extra Cheese', 'medium')
takeOrder('Bacon', 'EXTRA THICK')

I get the output I want, which is:

Order: thin pizza topped with peperoni 7.5

Order: medium pizza topped with extra Cheese 15

Order: EXTRA THICK pizza topped with Bacon 22.5

But why? How do Javascript knows how many orders there are in the code?
My guess is that because orderCount = orderCount + 1; and:

takeOrder('peperoni', 'thin');
takeOrder('extra Cheese', 'medium');
takeOrder('Bacon', 'EXTRA THICK');

But, I'm really not sure. I would much rather know why my code works :)

  • 1
    Javascript uses a scoping system similar to c or java. Your orderCount variable is in the global scope so therefore all functions have access to the orderCount variable. You can refer to https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – David Jul 30 '17 at 16:50

2 Answers2

1
    var orderCount = 0

You initialize orderCount with 0.

    function takeOrder(topping, crustType){
     orderCount = orderCount + 1; 
     /* more code here */
    }

Every time this function is invoked, +1 to orderCount.

    takeOrder('peperoni', 'thin');

Current orderCount = 0, takeOrder is called, so orderCount = 0 + 1

    takeOrder('extra Cheese', 'medium');

Current orderCount = 1, takeOrder is called again, so orderCount = 1 + 1

    takeOrder('Bacon', 'EXTRA THICK')

Current orderCount = 2, takeOrder is called again, so orderCount = 2 + 1

Since you invoked the function 3 times, the final orderCount is 3.

yuenhy
  • 41
  • 1
  • 8
0

In short you are using a shared variable, like local storage, to pass data between functions. Please read about variable scoping in javascrpt to know more.

orderCount variable is of global scope. So you can access it from any function (something like static variable in java/C). Every time you are executing takeOrder function you are incrementing this variable by one. When you are executing getSubTotal function, you are reading it's value and printing order total price.

Your scenario: With first takeOrder execution you have incremented orderCount to 1, then 2, and 3. When you are executing getSubTotal functinon, you are reading your global variable value (3) and computing total price.

Tip: When you will continue your tutorial, you will learn that it's better to wrap both methods inside an object, and add your variable inside of this object, rather than global variable. Because more global variables you have, harder it becomes to work with them.

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57