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.
Here are a few rules for naming your variable:
- Start with a letter (lowercase or uppercase),
- Contain only letters, numbers,
_. 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;
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:
void). Strings must be in quotation marks.