Why You Should Use Var

Click on the Display1 button, read the message box and close it. Then click on the Display2 button - read and close. Then click on the Display1 button again.



<SCRIPT>

var func1 = "This is the global variable named func1";

function Display1() {
    
alert(func1);
}

function Display2() {
    
func1 = "This is local variable named func1";

     alert(func1);
}

</SCRIPT>

 <FORM>
 
 <INPUT TYPE="button" NAME="ButtonDisplay1" VALUE="Display1"

  
  
onClick="Display1();">
 
 <INPUT TYPE="button" NAME="ButtonDisplay2" VALUE="Display2"
     
onClick="Display2();">
</FORM>

NOTE: func1 is a global variable. In Display2() func1's value gets changed. To make func1 in Display2() a local variable we need to declare the variable within the function.

function Display2() {
     var
func1 = "This is local variable named func1"; // now func1 is a local variable