Bright Java Tutorial

is brought to you by DoITBright LLC

Javascript

Declaring Variables

A variable is a name that we give to represent a certain value. We may or may not know what it's initial value is. A variable may change it's value over time. For example, we can call the price of an item as 'itemPrice'. One day, we went to the store to buy 10 items of the same kind. We ended up paying for it for 30 dollars. How much is the price of the item? Since we spent 30 dollars for 10 items. We can say itemPrice = Total Price / number of items. In this case, the answer is 3 dollars. Let us now put this into a Javascript code.

  <html>
    <head>
      <title>Declaring Variables In Javascript.</title>
    </head>
    <body>
       If 10 chocolate bars costs 30 dollars, then <br/>
       <script type="text/javascript">
         var itemPrice = 30 / 10;
         document.write("1 chocolate bar is " + itemPrice 
             + " dollars.");
       </script>
    </body>
  </html>
                           

Javascript is a loosely typed language. What this means is, we don't have to tell what kind of variable we are trying to declare. The type of the variable may even change along the way. Let us add more code to our previous example.

  <html>
    <head>
      <title>Declaring Variables In Javascript.</title>
    </head>
    <body>
       If 10 chocolate bars costs 30 dollars, then <br/>
       <script type="text/javascript">
         var itemPrice = 30 / 10;
         document.write("1 chocolate bar is " + itemPrice 
             + " dollars.");
         itemPrice = itemPrice + ' dollars';
         document.write("1 chocolate bar is " + itemPrice);
       </script>
    </body>
  </html>
                           

You might have noticed that to declare a variable, we are using the reserved word 'var' then followed by the variable name. Removing the keyword 'var' during the declaration of the variable might work in a lot of cases but you might encounter problems in the future. It is highly advisable to use the keyword 'var'.


Back    Next