JavaScript Global Variable
Photo by NASA on Unsplash Edited by Author

JavaScript Global Variable

javascript global variable example

6 min readJun 29, 2023

--

What is JavaScript Global Variable?

A JavaScript global variable is a variable that is accessible from anywhere in your JavaScript code, regardless of where it is declared. It means that the variable’s scope extends throughout your entire program, allowing you to use and modify its value from different functions, blocks, or scripts.[1]

When you declare a variable outside of any specific function or block, it becomes a global variable. This means that it can be accessed and modified from anywhere within the JavaScript code, including other functions, event handlers, or even external scripts.

Global variables are useful when you need to store data or values that need to be shared and accessed by multiple parts of your code. They provide a way to maintain a shared state or share information across different components of your application.

JavaScript Global Variable Example

Let’s imagine a real-world scenario to explain JavaScript global variables.

Imagine you are building a website for an online store called “TechWorld.” The website has different sections, such as a product page, a shopping cart, and a user profile section.

JavaScript Global Variable
Image by Author

In this scenario, you want to keep track of the user’s login status throughout the website. You need to display whether a user is logged in or not, and you want them to access this information from any part of the website.

To achieve this, you can use a global variable in JavaScript. Let’s call it `isLoggedIn`, and it will hold a Boolean value indicating the user’s login status.

// Define a global variable for login status
var isLoggedIn = false;

Now, whenever a user logs in or logs out on your website, you can update the `isLoggedIn` variable accordingly.

// User logs in
isLoggedIn = true;
// User logs out
isLoggedIn = false;

Since `isLoggedIn` is a global variable, you can access it from any part of your website’s JavaScript code. For example, you might want to display different content or show specific buttons based on whether the user is logged in or not.

// Display different content based on login status
if (isLoggedIn) {
console.log("Welcome, user! You are logged in.");
// Display user-specific content
} else {
console.log("Welcome, guest! Please log in.");
// Display general content
}

In this case, the global variable `isLoggedIn` helps you determine which message to display and what content to show based on the user’s login status. It allows you to make decisions and customize the user experience throughout the website.

By using a global variable, you ensure that the login status information is easily accessible from any part of your JavaScript code, enabling consistent behavior across different sections of the website.

However, remember that global variables should be used thoughtfully, as excessive reliance on them can make your code harder to manage and lead to potential conflicts. It’s generally recommended to limit their use and consider alternative approaches like encapsulation and modular programming.

How to know if a Variable is global or not?

In JavaScript, you can determine if a variable is global or not by considering its scope and where it is declared. Here are a few ways to determine if a variable is global.

Location of Declaration

If the variable is declared outside of any function or block{}, it is likely a global variable. Global variables are declared in the global scope and are accessible from anywhere within the script.

Window Object (in Browser Environment)

In the browser environment, global variables are attached to the `window` object. You can check if a variable exists as a property of the `window` object. For example, if you have a variable named `myVariable`, you can check if it is a global variable with

`window.hasOwnProperty(‘myVariable’)`

Here’s an example to illustrate these points:

let globalVariable = 'I am global';
function myFunction() {
let localVariable = 'I am local';

console.log(globalVariable); // Accessible, prints 'I am global'
console.log(localVariable); // Accessible, prints 'I am local'
}
console.log(globalVariable); // Accessible, prints 'I am global'
console.log(localVariable); // Not accessible, throws ReferenceError
console.log(window.hasOwnProperty('globalVariable')); // true
console.log(window.hasOwnProperty('localVariable')); // false

In the example above, `globalVariable` is declared outside any function, making it a global variable. It can be accessed from both the `myFunction` and the top-level scope. On the other hand, `localVariable` is declared within the `myFunction` function and is only accessible within that function’s scope. Trying to access `localVariable` outside of `myFunction` results in a ReferenceError.

The ‘var’ exception

When a variable is declared with the `var` keyword outside of any function or block{}, it becomes a global variable. In other words, the variable is accessible from anywhere within the JavaScript code.[2]

Here’s an example illustrating the global scope of a variable declared with `var`:

// Example 1
var myGlobalVariable = "I am a global variable";
function myFunction() {
console.log(myGlobalVariable); // Accessible, prints "I am a global variable"
}
console.log(myGlobalVariable); // Accessible, prints "I am a global variable"

// Example 2
function myFunction() {
var myGlobalVariable = "I am a global variable";
console.log(myGlobalVariable); // Accessible, prints "I am a global variable"
}
console.log(myGlobalVariable); // Accessible, prints "I am a global variable"

In the example above, `myGlobalVariable` is declared with `var` outside of any function, making it a global variable. It can be accessed and used from both the `myFunction` function and the top-level scope.

However, it’s worth noting that in modern JavaScript, the `let` and `const` keywords are preferred over `var` due to their block scope. `var` has function scope or global scope, whereas `let` and `const` have block scope, which provides more predictable and controlled variable scoping behavior.

How to use it in code?

Sure! In simple terms, a JavaScript global variable is a variable that can be accessed from anywhere in your JavaScript code. It means that the variable is not limited to a specific function or block of code, but instead, it can be used throughout your entire program.

Here’s an example to help you understand:

// Define a global variable
var myGlobalVariable = "Hello, world!";
// Access and use the global variable
function sayHello() {
console.log(myGlobalVariable);
}
// Call the function
sayHello(); // Output: Hello, world!
// You can also access the global variable outside of functions
console.log(myGlobalVariable); // Output: Hello, world!

In the example above, `myGlobalVariable` is declared at the top level of the code, outside of any function. This makes it a global variable. It can be accessed and used both inside and outside of functions. In the `sayHello()` function, we simply output the value of `myGlobalVariable` using `console.log()`. When the function is called, it prints “Hello, world!” to the console.

Later, outside of the function, we again access the global variable and print its value using `console.log()`, which gives the same output.

The Bottom Line

A JavaScript global variable is a variable that is accessible from anywhere within the code, regardless of where it is declared. Global variables are declared outside of any specific function or block, making them accessible throughout the entire program.

While var can be used to declare global variables, it is recommended to use the let or const keywords for variable declarations due to their block scoping, which provides more control and predictability.

Using global variables can provide convenience and accessibility, as they allow sharing and accessing data from different parts of the code. However, it is important to exercise caution when using global variables, as overuse can lead to potential naming conflicts, code maintainability issues, and a lack of encapsulation.

You may also like:

7 Habits of a Successful Programmer

Should I learn Java or JavaScript?

--

--