Global variable in JavaScript

How to make a global variable in JavaScript?

I need the variable that was declared in one function to work in another function.

Example: JSFiddle

$("#div3").click(function() {
    var fill = "a";
});


$("#div2").click(function() {
alert(fill);
});

When I click on #div3 the variable works on alert of #div2!

Author: Maniero, 2014-09-11

3 answers

Are you sure you want to do this? Not a good indication. It is always preferable to find a solution to pass this value in some other way. At least encapsulate in a global function.

If you really want to, declare it outside the function and without the var. It will be accessible globally. The statement without var makes the variable global implicitly. So it could even be declared inside the function without var which would be global of the same jetio, but it could become more confusing.

fill = "";

$("#div3").click(function() {
    fill = "a";
});


$("#div2").click(function() {
alert(fill);
});

If you do not want it to be global, but only accessible in both functions you can use var (more recommended than leaving global):

var fill;

$("#div3").click(function() {
    fill = "a";
});


$("#div2").click(function() {
alert(fill);
});

In this way, in thesis, at least the scope becomes more limited. The variable fill will be available in both functions but not elsewhere in the script. Probably this form already solves what you want. Still it is not the most suitable. always prefer to pass variables by parameter.

Because global variables are bad

JavaScript uses lexical scope for explicitly declared variables (with var), i.e. the visibility of a variable is where it was created. A variable does not leak out of the "nesting" that it was declared, but is present in all nests inside the place where it was created with the declaration.

To be clear, an explicitly declared variable uses the var Command and it is recommended that all as variables are declared this way. The other way to declare a variable is implicitly, that is, without any command, you assign a value to a variable and if it does not exist, it is created, if it exists, it changes the existing value. Have you noticed how confusing this can be?

The second example I showed is much better because it does not suffer from this problem. Although it may not make much difference if the location you are declaring is not a function. The scope out of any function does not cease to be a global scope. So if these two functions you are declaring are not within other functions (or modules in the EcmaScript 6), putting the var to a declare the variable fill will have the same effect as not using the command and leaving it implicitly global. But putting var is a little better because at least it makes clear the intention to create a new variable.

Passing arguments through parameters is always recommended to avoid that you access data unintentionally, that you access something that wasn't quite what you wanted. And worse, if it is a variable passed by value, let it not be changed without your desire. Parameters that are passed by value (if it is from numeric or string, for example) can be manipulated within a function without risk of changing the variable that was used to pass as an argument in the function call. The parameters by reference (array and object) change the value and the manipulations that occur within of the function remain in the variable when it closes.

If you handle a variable inherited by lexical scope or implicitly declared Global, the value remains and may not be what you want. even when you think it's what you want. You create side effects and bugs that are difficult to locate.

When using a parameter we can say that the parameter is the variable declaration and a variable declaration must be very close to the its use to avoid confusion. When you declare a little distant, even if little, the confusion already begins. And the farther away the more confusing and more difficult to synchronize all manipulations without causing problems.

You can create an artificial scope even in the current version. See the final example in the mgibsonbr response How to create an artificial scope and limit variable access.

For more information see essa and essa response.

 35
Author: Maniero, 2020-09-08 18:00:03

In JavaScript, a variable is global in the following situations:

  1. It was declared without using var:

    fill = ""; // Globalmente acessível
    
  2. It was declared using var, but at top-level (i.e. without being inside any function):

    var fill = ""; // Globalmente acessível
    
  3. It was created by assigning a property to the global object (which in the browser is window):

    window.fill = ""; // Globalmente acessível
    
    window["fill"] = ""; // Globalmente acessível
    

Otherwise it is local to the function in which it was defined. Note what function parameters work as local variables. Local variables to a function are accessible within it and within any function defined in its body (see closure).

$(document).ready(function() {
    var fill = ""; // Acessível somente dentro dessa função
});

There is no block scope in JavaScript, so variables created within a block will be visible in its outermost scope:

function teste() {
    for ( var x = 10 ; x < 20 ; x++ ) { // x é acessível em qualquer lugar dentro da função
        var y = 42; // y é acessível em qualquer lugar dentro da função
    }
}

for ( var x = 10 ; x < 20 ; x++ ) { // x é globalmente acessível
    var y = 42; // y é globalmente acessível
}

Thus, if you want your variable to be accessible in two different functions, you can declare it in your common scope (as suggested in the Maniero answer )-taking care that this scope is not the top-level (in which case the variable would become global with or without the var). Alternatively, if you want to narrow the scope further, you can create a closure specific to these two functions:

(function() {
    var fill; // Não é acessível fora desse closure

    $("#div3").click(function() {
        fill = "a";
    });

    $("#div2").click(function() {
        alert(fill);
    });
})();
 23
Author: mgibsonbr, 2017-11-01 11:19:03

When I need to use a global variable in JS I do as follows:

top.fill = "";

$("#div3").click(function() {
    top.fill = "a";
});


$("#div2").click(function() {
    alert(top.fill);
});

I believe that vc should have the expected result.

 2
Author: Fonseca, 2014-09-15 13:49:35