By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

JavaScript Variables

How to declare and work with Variables, and about what they are used for.

Edited: 2011-11-09 10:04

JavaScript variables can be used to store information temporarily, the information stored in variables will only be accessible as long as there are still code that refers to them. Variables are usually declared before they are used, like done below.

var my-variable = '';

This would set the variable's content to an empty string. The first time you use a variable, its a good idea to declare it first, this is done using var in front of it. Following uses of the variable doesn't need the var part.

JavaScript have different types of variables. Variables can either contain strings or integers (numbers), but they can also contain arrays.

Variables not working?

Keep in mind that variables need to exist before you can use them. So don't declare them in the body, to try and use them in the head, it will not work. The scripts in the body are loaded after the scripts in the head.

Variables in JavaScript are also case sensitive, and may only contain letters and numbers.

Variables example

Below is an example throwing out a popup with a message contained in a variable. This is done by first creating a user function, and then calling it using the onclick event on a button.

<!DOCTYPE html>
<html lang="en-US">

    <title>JavaScript popup alert Vision</title>
    <script type="text/javascript">
     function butt() {
      var reply = 'The button was Pressed';

   <input type="button" onclick="butt()" value="Press Me">


Brugbart Vision!