Variables in a programming language are similar to those in Mathematics in one manner: a variable is some named entity that has no fixed value. The digit 9, for example, is not a variable because it has a fixed value. On the other hand, we can say x=6
is a variable because it can be re-assigned a new value whenever required. A variable is important only when it has been assigned a value.
Variable Naming Rules
. Thus, totalCost
refers to a different variable then both TotalCost
With regard to variables two things are very important: Scope and Data Type.
Scope of a Variable
Programming languages usually allow two broad types of variables: local and global
. A local variable is one that can be used in a single function. If you try to change / read the value of a local variable from outside that function, an error will be reported. A global variable, as the name suggests, can be read / changed from any function on a single page.
You don’t need to do anything special to incorporate scope of a variable – its automatically handled for you. A variable that is defined in a function (we will see how to define a variable shortly) is local. A variable defined outside any function is global. These logical concepts are simply for making you a better programmer.
A variable is defined as var variableName;
. The part var
and the semicolon are part of the syntax and will always be used like this. variableName
is the name of the variable that you want to define.
Values are assigned as variableName = value
. For example to mean “let i be equal to 10”
, we write i=10;
. Some examples are given below:
name = "Muhammad Ali Shah"; // alphanumeric
i = 5*10; // an integer
. In this case, 5.0
is a real (recall your Arithmetic lessons) and 1
- Undefined: A variable is said to have an undefined data type when it has been defined using a var statement but not given any values – that is, we cannot tell the data type of totalCost by seeing var totalCost.