A variable can be thought of as a container that holds data. It’s called a “variable” because the data it contains—its value—varies depending on your script. For example, you might place the total price of items a customer is buying in a variable, and then add tax to this amount, storing the result back in the variable. The type of a variable describes the nature of the data stored. For example, the type of a variable holding the value 3.14 would be number while the type of a variable holding a sentence would be string. Note that “string” is programming language lingo for a sequence of characters—in other words, some text.
You can now store data in the variable known by the identifier firstName. Presumably, you’d be storing a string here. We could then assign a value like "Thomas" to the variable. We call the string "Thomas" a literal, which describes any data appearing directly in the source code. The complete example is now
var firstName; firstName = "Thomas";
The illustration here demonstrates all the terms used so far together.
lastName = "Schneider";
Many programmers use this type of implicit declaration to save time when coding. It’s faster and easier to not bother declaring variables before using them. Unfortunately, it’s also not a good idea. Scripts written without variable declarations are significantly harder to read than those that use explicit declarations. Implicit declaration can also lead to subtle, hard-to-find errors involving variable scope, a topic we’ll discuss later in the chapter. Unless you’re writing a very simple script (less than a dozen lines), always explicitly declare your variables.
var favNumber : number;
Given this example, an assignment like
favNumber = 3;
would be perfectly valid. But if you assigned some non-numeric type to the variable like
favNumber = "San Diego";
it would cause an error or warning to occur. It should start to become clear that weak typing provides some simplicity since programmers don’t have to worry about types, but it does so at the expense of runtime errors and security issues. We’ll see many issues with weak typing throughout both the chapter and the book. For now, the concept is enough. Let’s begin to look at each of the types in turn.