Search code examples
javascriptglobal-variables

Accessing variables from other functions without using global variables


I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.

If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?


Solution

  • To make a variable calculated in function A visible in function B, you have three choices:

    • make it a global,
    • make it an object property, or
    • pass it as a parameter when calling B from A.

    If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:

    function A()
    {
        var rand_num = calculate_random_number();
        B(rand_num);
    }
    
    function B(r)
    {
        use_rand_num(r);
    }