Javascript Tutorial -- Using Variables in Javascript



In our first example, we created a script to display the ubiquitous "Hello, World!" message on the user's web browser. Suppose we didn't always want to say "Hello, World!"? What if we wanted to say "Hello, George!" or maybe "Hola, Luisa Maria Castanella!" or perhaps even "Konichiwa, Watanabe Yasuhiko!"?

Fortunately, all modern programming languages of which I am aware (and this includes Javascript) have the capability of storing data in "variables" where they can be used and reused within the program. All you have to do to use a variable (as opposed to literal data) in Javascript is:
  1. Declare the variable;
  2. Define the variable; and
  3. Use the variable.

Here's how you do it:
        <script type="text/javascript">
          <!--
            var MyVariable

            MyVariable="Hola!  Se habla espanole?"
            document.write(MyVariable)
          //-->
        </script>
      
In some cases -- if you know the initial value of the data when you declare the variable -- steps 1 and 2 can be combined into a single step, like this:
        <script type="text/javascript">
          <!--
            var MyVariable="Hola!  Se habla espanole?"

            document.write(MyVariable)
          //-->
        </script>
      
If you've ever used other programming languages like C or Pascal, you will notice that Javascript does not require you to define the type of data you will be storing in the variable. Languages like C or Pascal are called "strongly typed" languages; languages like Javascript, Perl or Python are called "loosely typed" languages. Strongly typed languages are more efficient, since the compiler doesn't have to look at the context of the variable to determine how much storage to allocate to each variable, but loosely typed languages are more flexible -- you can store integers, floating point numbers or text in a single variable at different points in the program. While this...:
        <script type="text/javascript">
          <!--
            var MyVariable

            MyVariable="Guten Morgen!"
            document.write(MyVariable)

            MyVariable=3.141592653589
            document.write('PI = ' + MyVariable)

            MyVariable=2007
            document.write('This document was created in ' + MyVariable)
          //-->
        </script>
      
...would cause an error in C, it is perfectly acceptable in Javascript.

Here is an example of a script that uses variables.