Search code examples
javascriptglobalhoisting

What is the proper way to declare global variables


I know about hoisting.

But I wonder what the recommended solution is for a global array, for instance, that functions as a lookup table. An array that you would declare constant and make global in most languages.

Like:

 var lookup = ["010101010", "0100101010", "01010101010", "etc"];

 function foo() {    
     // lookup is undefined
 }

I could pass it in, I guess. Or make it part of window.document. Or some trick with 'this' that I don't fully understand. What's the best way to do this?

Edit: Right, after reading the comments, I now realize, the problem I was experiencing wasn't caused by hoisting. There was some other problem in my code. It works now. Thanks for clearing that up.


Solution

  • Just make sure that you declare lookup before the function foo is called. See the following snippet. If you declare it after foo is called, you will get the error undefined.

    var lookup = ["010101010", "0100101010", "01010101010", "etc"];
    foo();
     function foo() {    
         console.log(lookup);
     }