# Variables coordinate code fragments

Keywords:

In an event-drive program, the code is broken into pieces. Some runs when the page loads, some when different buttons are clicked.

Variables are how the different code fragments work together. When one piece of code changes a variable's value, the next piece of code will use that new value.

You'll see this in almost every example. To write the code for an event, start by working out how it changes variables. That's half the battle.

Here's some code from one of the examples.

1. <script>
2.     "use strict";
3.     var CoffeeChocolate = CoffeeChocolate || {};
4.     (function($) { 5. var coffeeExpense = 0; 6. ... 7. CoffeeChocolate.showCurrentExpenses = function() { 8.$("#coffeeExpense").html(coffeeExpense);
9.             ...
10.         };
11.         CoffeeChocolate.recordNewExpenses = function() {
12.             ...
13.             coffeeExpense += parseFloat(newCoffeeExpense);
14.             localStorage.setItem("coffeeExpense", coffeeExpense.toString());
15.             ...
16.         };
17.         CoffeeChocolate.resetExpenses = function() {
18.             ...
19.             coffeeExpense = 0;
20.             ...
21.             }
22.         };
23.         $(document).ready(function () { 24. ... 25. if ( localStorage.getItem("coffeeExpense") ) { 26. coffeeExpense = parseFloat(localStorage.getItem("coffeeExpense")); 27. } 28. ... 29. }); 30. }(jQuery)); 31. </script> The variable coffeeExpense is the first thing inside the wrapper: (function($) {
var coffeeExpense = 0;
...
}(jQuery));

All of the code fragments are inside the wrapper, so coffeeExpense is available to every code fragment. They all use the variable.