What Are JavaScript Variables?

By: Dusty Arlia
Published on August 16, 2012
Last Updated on Saturday, July 11, 2015 at 8:35 PM
Total Updates: 7

A variable is a named container to store information. You can store a number, a string, a Boolean, or any other data type value in a variable. Variables become extremely helpful when you have a piece of information that changes over the course of the program's lifetime (hence the name variable for information that can vary). Even though you can change what's inside the container, it still remains inside the same container.

When you create a variable, you use the JavaScript keyword var. For example:

var total;

The var keyword creates (or declares) the variable and total is its identifier.

Here are a few rules for naming your variable:

  • Start with a letter (lowercase or uppercase), $, or _.
  • Contain only letters, numbers, $, and _. No special characters like #, @, *, or spaces.
  • Variables are case-sensitive.
  • Don't use keywords.

When you create your variable name, you should consider the value that variable will hold. Then you should come up with a descriptive name that best describes the information stored in that variable. By choosing a good name for your variable, your program will be easier to understand. Using camelcase or underscores (_) can make your variable names easier to read. For example:

var firstName;      //camelcase
var first_name;     //underscores
var firstname;      //this is slightly harder to read

When storing values in variables you can do it with one statement or two. For example:

var first_name;         //declares the variable
first_name = 'Dusty';   //assigns it a value


var first_name = 'Dusty';    //all in one statement

You can also declare multiple variables in one statement:

var firstName, middleName, lastName;

You can even declare and store values into multiple variables with one JavaSCript statement:

var firstName = "Dusty", middleName = "Tito", lastName = "Arlia";

When you set the value of your variable in your declaration, this is referred to as "initialing your variable". With the value of your variable set, you can now access the value stored in that variable by using the variable's name (its identifier). When referencing a variable, quotation marks are not necessary. For example:


The JavaScript interpreter treats words without quotation marks as either variable names, JavaScript keywords, or certain operators (like delete, in, instanceof, new, typeof, or void). Strings must be in quotation marks.