Passing javascript variables from one function/file to another

3.8k views Asked by At

I have a function with lots of variables and very big arrays being defined; this makes the function very large and hard to work with. How can I define the variables/arrays in another file and use them in this function?

Example:

DoStuff.js:

function genList(){
    var listData = [

    //lots of inner arrays and data

    ]

    var dataItem = "value";//50 of these

    //do stuff with the data
}

What I'm trying to do:

ExternalData.js:

var listData = [

//lots of inner arrays and data

]

var dataItem = "value";//50 of these

DoStuff.js:

function genList(){

//call variables/arrays from ExternalData.js

//do stuff
}

Note: JQuery is applicable here, but I'd rather not call any other libraries for something so small.

1

There are 1 answers

6
limoragni On BEST ANSWER

I would define all the variables in an object for example:

var obj = {
   array_one: ['x', 'y'],
   some_value: 'z'
}

This method has the advantage of make a kind of namespace for all the variables, saving you from overriding values.

And then use that object into my code using some kind of include method.

One simple method could be to add the script before the one you are writing like this:

<script type="text/javascript" scr="file_with_object.js"></script>

Other more sophisticated but only advisable if you are going to repeat this kind of behavior is to use a Library or a framework to make includes more concise, require.js is a good example

EDIT: In the previous example I used the object with var considering that the code was written on the global scope, I think it would be better to use window.obj = {} to ensure the variable is global. And, just for the record, any variable you define like this window.somevariable is going to be a global variable. Once you define a global variable you could use it anywhere in your code (after the definition takes place). The namespace is the right way to go though.

EDIT 2: I think this post is more about scope than includes. When you declare a variable this way: var some_variable; you are saying that you want to bind that variable to the current scope. So if you do that inside a function, that variable "lives" inside that function:

var some_var = 10;
function(){
   var some_var = 5;
   console.log(some_var) // 5
}

console.log(some_var) // 10

But if you declare the variable without the var on both cases you are making that varaible global the first time and overriding its value on the second:

    some_var = 10;
    function(){
       some_var = 5;
       console.log(some_var) // 5
    }
    console.log(some_var) // 5

And alway you declare a varaible without the var, that variable is accessible trough window.variablename, because you are not binding the variable to any particular scope, so the binding is made to the window objecy, which is the global scope "namespace".