Javascript
  1. Javascript intro
  2. Javascript basics
  3. Javascript variables
  4. Javascript functions
  5. Javascript popup boxes
  6. Javascript conditions
  7. Javascript loops
  8. Javascript arrays
  9. Javascript objects
  10. Javascript strings
  11. Javascript events
  12. Javascript errors
  13. Javascript DOM
  14. Javascript elements
  15. Javascript new windows
  16. Javascript date & time
  17. Javascript cookies
  18. Javascript print
  19. Javascript redirect
  20. Javascript void
  21. Javascript summary

Javascript variables

Variables are a fundamental concept in many computer languages and knowing how to work with them is essential knowledge.

This tutorial focuses on:

What is a variable?

A variable is a container which stores information in a computer's memory. The value of a variable can change all throughout a script.

Declaring variables

In Javascript, a variable is declared with the var keyword.

Syntax:
var varName;
Example:
<script type="text/javascript> var aNumber; </script>

In the above example, a variable named aNumber is declared. You can assign a value to a variable at the same time that it is declared. This process is known as initialization.

Initializating a variable example:
<script type="text/javascript> var aNumber = 5; </script>
Declaring a variable and then giving it a value example:
<script type="text/javascript> var aNumber; aNumber = 5; </script>

NOTE: The var keyword should be used only once with each variable - during declaration. After a variable has been declared or initialized, you can refer to it by its name without the var keyword.

Naming variables

When naming variables, several rules should be followed:

Printing variables

Variables are printed by including the variable name in a document.write() command. When printing the value of a variable, the variable name should NOT be included in double quotes.

Example:
<script type="text/javascript"> var numChairs = 5; document.write(numChairs); </script>
Output:
5

You can also print variables together with regular text. To do this, use the + symbol to join the text and variable values together.

Example:
<script type="text/javascript"> var teamName = "The Penguins"; var teamState = "Connecticut"; var numWins = 12; var numLosses = 2; document.write("The name of the team is " + teamName); document.write("<br />The team is from " + teamState); document.write("<br />" + teamName + " have won " + numWins + " games and have lost " + numLosses + " games"); </script>
Output:
The name of the team is The Penguins The team is from Connecticut The Penguins have won 12 games and have lost 2 games
© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information