JavaScript Variables

JavaScript variables are used to store information that can be referenced and used by a script.

As with any programming language, JavaScript variables are a like a container that contains a value — a value that can be changed as required.

For example, you could prompt your website users for their first name. When they enter their first name you could store it in a variable called say, firstName.

Now that you have the user's first name assigned to a variable, you could do all sorts of things with it like display a personalized welcome message back to the user for example. By using a variable to store the user's first name, you can write one piece of code for all your users.

Declaring JavaScript variables

First, you need to declare your variables. You do this using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.

Different methods of declaring JavaScript variables

Using JavaScript variables

Although there are many uses for JavaScript variables, here is a quick and dirty example:

The above example opens a JavaScript prompt, prompting the user for their first name. It will then write the name to the page . In practice, you would output the name somewhere within the body element. You would also use a function for this type of thing.

I suspect you can find a much better use for your javascript variables but this simply to demonstrate how easily you can store data inside a variable — data that could change at any moment.

Rules for JavaScript Variables