Global variable in Javascript

Asked

Viewed 72,012 times

17

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 in the alert of #div2!

3 answers

36


Are you sure you want to do this? It is 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 out of function and without the var. It will be accessible globally. The statement without var makes the global variable implicitly. So it could even be declared within the function without the var that would be global of the same jetion, but could become more confusing.

fill = "";

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


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

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

var fill;

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


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

I put in the Github for future reference.

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

Because global variables are bad

Javascript uses lexical scope for explicitly stated 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 nests to the place where it was created with the declaration.

To make it clear, a variable declared explicitly uses the command var and it is recommended that all the variables are declared this way. The other way of declaring 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, changes the existing value. I can see how this can be confusing?

The second example I showed you is much better because you don’t have this problem. Although it may not make much difference if the location you are declaring is not a function. The scope outside 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), put the var to declare the variable fill will have the same effect as not using the command and leaving implicitly global. But put the var is 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 unintentionally accessing data, accessing something that wasn’t quite what you wanted. And worse, if it is a variable passed by value, it is not changed without its wish. Parameters that are passed by value (if they are numeric or string, for example) can be manipulated within a function without risk of changing the variable that was used to pass as argument in the function call. The parameters by reference (array and object) change the value and the manipulations occurring within 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 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 its use to avoid confusion. When you declare a little distant, even a little, the confusion begins. And the more distant 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 on response from mgibsonbr how to create an artificial scope and limit variable access.

For more information see that one and that one reply.

  • thank you!!!!!!!

  • @bigown, the answer is very good, but I disagree with the statement in the first paragraph after Because global variables are bad. I don’t know if your intention was to say that a variable with var doesn’t leak from nesting, the phrase didn’t make me clear this, but vase she is without the var, So yes, it leaks until it reaches the nesting top.level or window, just like I said in this answer.

  • 1

    @Guilhermelautert I put there but facilitate but the next paragraph explains what I’m talking about.

  • took away my doubt.

23

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

  1. She was declared unused var:

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

    var fill = ""; // Globalmente acessível
    
  3. It was created by assigning a property to the global object (that 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 that function parameters function 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
}

So if you want your variable to be accessible in two different functions, you can declare it in your common scope (as suggested in Maniero’s response) - 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 further narrow the scope, 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);
    });
})();
  • took away my doubt.

3

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

top.fill = "";

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


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

I believe you must have the expected result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.