Javascript: Global variables

This entry is part 10 of 27 in the series Javascript Tutorial

The scope containing all of a program is called global scope.

This is the scope you are in when entering a script.  When you define a variable here, the variable can be accessed by all functions.

Inside the global scope, you can create a nested scope by defining a function.

<!DOCTYPE html>
<html>
<head>
    <title>Global Variables</title>
    
    <script>
        var global_str = 'I am a global string';

        function updateFunction() {
            var local_str = 'I am a local string';
            document.getElementsByTagName('p')[0].innerHTML = local_str;
        }
    </script>

</head>
<body>
<p>I am a string</p>
<button onclick='updateFunction()'>Click Me</button>
<br>
<script>
    document.write(global_str);
</script>
</body>
</html>
Series Navigation<< Javascript: A loosely typed language
Javascript: The getElementById() method >>