Variables


 

JavaScript functions explained
JavaScript variables explained
JavaScript handlers explained
JavaScript parameters explained
A Tutorial about the rollover code
Frequently asked questions

 

 

Every programming language has to have a means of storing information and JavaScript is no exception; variables are the 'containers' that hold the information. A variable can hold a string or a value; variables can be added together, joined, or they can be arrays, A variable can be local (only available to one function) or global (available to all scripts within a document). Variables declared in a function are local, while variables declared in the body of a document are global. It is good practise to declare a variable before it is used, this helps to keep the code neat, and makes it easier to debug.

The following script takes the name that the user types into the dialog box and puts it into the variable called MyVar. It then displays MyVar in the alert box.
  <SCRIPT>
	  MyVar =prompt("Please enter your name ","Type here")
	  alert("Hello "+MyVar+" hope you are enjoying this tutorial")
  </SCRIPT>
		 
Click on the button to see what the script does

The naming of variables is subject to the same rules as the naming of functions: - They are case sensitive; they must only start with a letter or underscore; and the names must not be the same as other variables, functions, or reserved JavaScript words. Finally, it helps if they are given a meaningful name that reflects the purpose of the variable. For example, a variable that holds the names of the image sources in a page, could be called 'x', but it would be easier for anyone reading the code if it was called 'imageList'.