A JavaScript global variable is declared outside the
function or declared with window object. It can be accessed from any function. Or
we can say that A variable declared
outside a function, becomes GLOBAL. A global variable has global scope: All
scripts and functions on a web page can access it.
var carName = " Volvo";
function myFunction1()
{
// code here
}
|
Automatically Global
If you assign a value to a variable that has not been
declared, it will automatically become a GLOBAL variable.This code example will
declare a global variable carName, even if the value is assigned inside a
function.
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<script>
myFunction();
document.getElementById("demo1").innerHTML = "display
" + carName;
function myFunction() {
carName = "Aulto";
}
</script>
</body>
</html>
|