Local and global variables

Local varaibles are defined inside function with var keyword.
Global variables are defined outside function body and are visible in all document.

Example of Java script using local and global variables:


Java Script code:

In header of the file I define two global varibles:
<script language = "JavaScript">
<!--
var child = "Ala" //GLOBAL
var cat = "Milky" //GLOBAL
// -->
</script>
and function:
<script language = "JavaScript">
<!--
function apet() {
//Overriding global variables:
var child = "John" //LOCAL
var output = cat + "does not belong to "+ child +".<br>"
document.write(output)
}
// -->
</script>
In body section I use global variables:
<script language = "JavaScript">
<!--
apet()
document.write(cat + " belongs to " + child + ".")
//uses GLOBAL variables
// -->
</script>

Back to Java script list


Back to main page