EDDYMENS

Published 9 months ago

What Is A Global Variable?

Table of contents

Definition

With the premise that a variable [→] is used to describe an entity used to store data, a global variable is a stored value that is accessible anywhere within your source code [→].

Example

How global a variable gets depends on how scoping [→] works in the programming language you are working with and how wide it allows you to make variables.

Let's take a look at an example in Javascript.

01: 02: function area() { 03: window.height = 3; 04: window.width = 2; 05: return height*width; 06: } 07: 08: console.log(area()); // 6 09: console.log(height, width); // 3 2 10:

In the above code, we define two global variables window.height and window.width within the area function. By defining the variables as part of the window object we make them globally accessible. On line 08 we print out both the height and width variables even though we are outside the area function.

01: function area() { 02: 03: var height = 3; 04: var width = 2; 05: return height*width; 06: } 07: 08: console.log(area()); // 6 09: console.log(height, width); // height is not defined

In the second example above we still define both height and width , but this time we limit them to the function using the var keyword.

And since both variables are not publicly accessible we end up with an error message on line 09 when we try to print them out.

Summary

Typically you want to have fewer globally accessible variables as possible. This is to prevent them from accidentally overriding or being overridden by another definition.

Here is another article you might like 😊 What Is Scoping In Programming?