Variables are fundamental to all programming languages. They are data items that represent a memory storage location in the computer. Variables are containers that hold data such as numbers and strings. Variables have a name , a type , and a value .
num = 5; // name is "num", value is 5, type is numeric friend = "Peter"; // name is "friend", value is "Peter", type is string
Computer programming languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it. For example, if you are going to assign an integer to a variable, you would have to say something like:
int n = 5;
And if you were assigning a floating-point number:
float x = 44.5;
n = 5; x = 44.5;
3.2.1 Valid Names
Table 3.2. Valid and invalid variable names.
3.2.2 Declaring and Initializing Variables
Variables must be declared before they can be used. To make sure that variables are declared first, you can declare them in the head of the HTML document. There are two ways to declare a variable: either explicitly preceded by the keyword var , or not. Although laziness may get the best of you, it is a better practice to always use the var keyword.
You can assign a value to the variable (or initialize a variable) when you declare it, but it is not mandatory, unless you omit the var keyword. If a variable is declared but not initialized , it is "undefined."
var variable_name = value; // initialized var variable_name; // unitialized variable_name; // wrong
To declare a variable called firstname , you could say
You can declare multiple variables on the same line by separating each declaration with a comma. For example, you could say
var first_name, var middle_name, var last_name;
3.2.3 Dynamically or Loosely Typed Language
11 Name: Christian Dobbins 12 Age: 8 13 Ssn: undefined 14 Job Title: null 16 Now Ssn is: xxx-xx-xxx
3.2.4 Scope of Variables
It is often desirable to create variables that are private to a certain section of the program, thus avoiding naming conflicts and accidentally changing a value in some other part of the program. Private variables are called local variables. Local variables are created when a variable is declared within a function. Local variables must be declared with the keyword, var . They are accessible only from within the function from the time of declaration to the end of the enclosing block, and they take precedence over any global variable with the same name. (See Chapter 7, "Functions.")
3.2.5 Concatenation and Variables
var temp = "The temperature is " + 87; // returns "The temperature is 87" var message = 25 + " days till Christmas"; // returns "25 days till Christmas"
But, if both operands are numbers, then addition is performed:
var sum = 10 + 5; // sum is 15
3 25 cats 4 almost 25 5 29 6 510 years 7 30 dogs 8 dogs255