Bookmark and Share

JavaScript Variables

Variables in JavaScript behave the same as variables in most popular programming languages (C, C++, etc) do, but in JavaScript you don't have to declare variables before you use them. If you don't know what declaring is, don't worry about it. It isn't important!

Advertise on

JavaScript Using Variables

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.

HTML & JavaScript Code:

<script type="text/JavaScript">
var linebreak = "<br />"
var my_var = "Hello World!"


my_var = "I am learning JavaScript!"

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.

To assign a value to a variable, you use the equal sign (=) with the variable on the left and the value to be assigned on the right. If you swap the order, your script will not work correctly! In English, the JavaScript "myVar = 'Hello World!'" would be: myVar equals 'Hello World!'.

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.

JavaScript Variable Naming Conventions

When choosing a variable name, you must first be sure that you do not use any of the JavaScript reserved names Found Here. Another good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then name it "shoe_size" to make your JavaScript more readable.

Finally, JavaScript variable names may not start with a numeral (0-9). These variable names would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.

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).

Bookmark and Share

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials