A variable's purpose is to store information so that it can be used later. A variable is a symbolic name that represents some data that you set. To think of a variable name in real world terms, picture that the name is a grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it around a lot easier, but the name is not the data!
A Variable Example
When using a variable for the first time it is not necessary to use "var" before the variable name, but it is a good programming practice to make it crystal clear when a variable is being used for the first time in the program. Here we are showing how the same variable can take on different values throughout a script.
var linebreak = "<br />"
var my_var = "Hello World!"
my_var = "Script is Finishing up..."
We made two variables in this example--one to hold the HTML for a line break and the other for a dynamic variable that had a total of three different values throughout the script.
The first time we used a variable, we placed var in front to signify its first use. This is an easy way to organize the variables in your code and see when they came into existence. In subsequent assignments of the same variable, we did not need the var.
A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder, etc).
Found Something Wrong in this Lesson?
Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!