Information Technology Reference
In-Depth Information
important to understand the difference between using a global variable and a local
variable.
In a nutshell, and I would like to take a moment to stress the fact that this is the most
basic of explanations, a local variable is a variable that can be used inside a function but
is not available for use inside of a different function or as a part of your script. Functions
are basically “short-cuts” that can be reused. For example, I might create a function that
does a bit of math on given input (called “function arguments,”that is, the information
you put inside () after a function call) and re-use that same function throughout my
code. Local variables are used inside function blocks but are not accessible outside.
Think of the inside of your function as a small world apart from the rest of your code in
terms of these variables!
A global variable, on the other hand, as you probably guessed by now, is accessible
globally so you can call it in any function or object in your JavaScript file. While there are
those out there that would scoff at the use of global variables because they can cause
problems down the line. For example, a global variable could be updated from a variety
of functions, causing confusion as to how the variable is changing during the debug
process. However, for the sake of learning, since this is a book for beginners, we will use
them in our examples.
Listing 3-5 sets up a list of global variables to be used throughout our JavaScript file, as
well as an array filled with rhyming demo choices to keep our users entertained for
hours... or minutes.
Listing 3-5. Javascript for I Love Ham -Part 1
/**
* I Love Ham
* @author: Rocco Augusto
* @file: js/main.js
**/
var correct = '';
var choice = '';
varresultLength = 0;
var tweets = [
['I love ham','Earthquake in Japan'],
['Android is awesome', 'I just hit an opossum'],
['Ice cream sandwich','I fell out of my hammock'],
];
Unlike our previous game, we will have a smaller array of choices to be presented to our
users. While I would have loved to add 50 to 100 different rhyming examples,
unfortunately I was only witty enough to create three off the top of my head. For the time
being, I think three is good, but if you are following along at home, try to put in as many
as you can think of! I'm sure a good lot of you are a bit more witty than I am!
Listing 3-6 walks up through the init() function of our application and grabs our
Twitter JSON feed from the API.
Search WWH ::




Custom Search