Global variable in JavaScript

16

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 !

    
asked by anonymous 12.09.2014 / 00:10

3 answers

33

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, declare it out of function and without var . It will be accessible globally. The declaration without var makes the global variable implicit. So it could even be declared inside the function without the var that would be global from the same location, but 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 global):

var fill;

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


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

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

Because global variables are bad

JavaScript uses lexical scope for explicitly declared variables (with var ), that is, 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 internal nestings where it was created with the declaration.

To make it clear, an explicitly declared variable uses the var command and it is recommended that all variables be 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 this can be confusing?

The second example I showed is much better because it does not suffer from this problem. While it may not make much difference if the location you are declaring is not a function. The scope out of any function is still a global scope. So if these two functions you are declaring are not within other functions (or modules in the EcmaScript 6 ), putting var to declare the variable fill will have the same effect as not using the command and leave 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 prevent you from inadvertently accessing data, accessing something that was not quite what you wanted. Worse, if it is a value-valued variable, let it not be changed without it being your wish. Parameters that are passed by value (if it is numeric or string , for example) can be manipulated inside a function without risk of changing the variable that was used to pass as argument in the function call. Already the parameters by reference ( array and object ) change the value and the manipulations that occur inside the function remain in the variable when it closes.

If you manipulate a variable inherited by lexical scope or declared implicitly 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 declaration of the variable and a declaration of variable must be very close to its use to avoid confusion. When you declare yourself a little distant, even if little, confusion already begins. And the further confusing and the more difficult to synchronize all the manipulations without causing problems.

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

For more information, see this and this answer.

    
12.09.2014 / 00:14
21

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

  • It was declared without using var :

    fill = ""; // Globalmente acessível
    
  • It was declared using var , but at the top-level (i.e. not within any function):

    var fill = ""; // Globalmente acessível
    
  • 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 where it was defined. Note that function parameters work as local variables. Local variables to a function are accessible within and within any function defined in your 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 their 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
    }
    

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

    (function() {
        var fill; // Não é acessível fora desse closure
    
        $("#div3").click(function() {
            fill = "a";
        });
    
        $("#div2").click(function() {
            alert(fill);
        });
    })();
    
        
    12.09.2014 / 00:53
    2

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

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

    I think you should have the expected result.

        
    15.09.2014 / 15:49