How to Define Global Variable in a JavaScript Function

A JavaScript variable is a container for storing data values. To declare a global variable, you can use the var at global scope like this:

w3docs logo Javascript global variable
let yourGlobalVariable = "global value"; //global variable function displayGlobalVal() { console.log(yourGlobalVariable); //global variable , result is "global value" } displayGlobalVal();

Alternatively, assign the property to a window because, in browsers, global variables declared with var are properties of the window object:

w3docs logo Javascript global variable
function display() { window.yourGlobalVariable = "global value"; console.log(yourGlobalVariable); } display();

In ECMAScript 2015 specification, let, class, and const statements at global scope create globals that are not properties of the global object.

However, avoid using the global scope and wrap your code in a scoping function and use local variables to that scoping function, and make your other functions closures within it like this:

w3docs logo Javascript global variable
(function () { // Begin scoping function let yourGlobalVariable = "global value"; // Global to your code, invisible outside the scoping function function display() { console.log(yourGlobalVariable); } display(); })(); // End scoping function

Global and Local Variables

Local function variables are declared inside a function in JavaScript. Local variables can be accessed only within the specified function. That is why, you can't reach them from any other function in the document.

It is recommended to use local variables in JavaScript functions because it allows using variables with the same name, as they are local variables that stay within separate functions. While using local variables, you can access them in the current function; in other words, the program will only access a variable in the scope of that variable.

All the variables created outside of functions are called global variables. These objects can be accessed throughout the website. They require different names for your global variables; otherwise, the browser will fail to display your desired action. Global variables have a global JavaScript scope. All functions can access it throughout the whole web page.