5

How can I force function to create global variable? I have this code:

$.ajax({
  url: 'https://dl.dropboxusercontent.com/s/11ofmbg4d4y3gb0/zakaznice_tyden.csv',
  dataType: 'text',
}).done(successFunction);

function successFunction(data) {
  var promenna = data.replace(/\n/g,";").split(";");
  var result = [];
  for (var i = 0; i < promenna.length; i+=2) {
  var line = [];
    line.push(promenna[i]);
    line.push(promenna[i+1]);
    result.push(line);
  }
  for (var i = 0; i < result.length; i += 1){
    $("#tyden" + i + "").append(result[i][0]);
    $("#tyden" + i + "kolik").append(result[i][1]);
  }
}

It loads csv file and create array from it. How can I make the array "line" globaly reachable?

David R
  • 14,711
  • 7
  • 54
  • 72
Ostrov
  • 129
  • 3
  • 12

3 Answers3

5

Scope It Outside Function Scope

The most common approach might be to simply declare it outside of the scope of a function if this is an option :

// This will be globally accessible from any child functions, etc.
var array = [];

function example(){
    // Your code here can access the array as expected
}

Implicit Global Declaration

If you want to declare a variable with global scope, just omit the var when declaring it, which will implicitly create it globally :

function example(){
    // This will be a global variable
    array = [];
}

Note: This will not work within strict mode, which does away with implicit globals. You can read more on about this approach here.

Storing the Variable

Another great approach would be to simply store the object as a property on the window object and access it from there as mentioned in Pamblam's answer.

Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

you can explicitly make any variable "global" by assigning it to the window object.

function things(){
    window.stuff = "junk";
}
things();
alert(stuff);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

Despite the fact that what you want is achievable, I do not recommend using global variables at all and encourage you to rethink your architecture. Global variables are hard to maintain and can cause errors.


var always creates a variable that has a function scope, so it means it's accessible in the function that it was declared in and all the functions inside that function (unless redefined inside them). If you want to make it global no matter where it is, you have a few options:

Direct assignment to non-existing variable

In case you run your code in non-strict mode, just drop the var. This will cause the lookup of variable line and since it's not declared in any context, it will assign it as a global variable. Example:

function fn() {
    line = 1;
}

fn();
console.log(line); //1

Two drawbacks though:

  • If you ran this code in a strict mode it would cause a ReferenceError
  • If there was a variable with same name in one of the outside functions, it would be overwritten and no global variable would be created

Example:

function outer() {
    var line;
    function inner {
        line = 8; //won't work because there is variable line in some outer context
    }
    inner();
}
outer();
console.log(line); //undefined

Assignment to global object

In every JS execution environment there is something called the global object. If you assign a property to it, you could use it as a global variable (except that it's not a variable - the difference is subtle, but there is). For example:

function fn() {
    window.line = 1;
}

fn();
console.log(line); //1;

This also has some drawbacks:

  • the global object is not necessarily hiding under window variable. In Node it's global and it may vary in other execution environments
  • in case there's a variable with name window (or global) declared on the way, it will override that variable (similar to drawback #2 from previous point)
  • you could use this to access the global object, but only in non-strict mode and only if this wasn't explicitly set (see rules for computing this value)

Indirect eval/new Function

Indirect eval and new Function are always executed as if they were declared directly inside the global scope. Although not elegant and error-prone (you code using strings), they do not suffer from previous drawbacks - work even in strict mode, no matter what variables have been declared on the way and independently from the execution environment. It's simple as that:

'use strict';
function fn() {
    //choose one of the following:
    //indirect eval:
    (0, eval)('line=1');
    //or new Function
    new Function('line=1')();
}

fn();
console.log(line); //1. Works even in strict mode

You may ask "why this weird (0, eval)(...) instead of just eval? That's what called indirect eval, and you can find more info about that under this SO answer


As you see, it is possible. But again, global variables make your code hard to maintain. You should limit the scope of line variable to the area it will be actually used.

Community
  • 1
  • 1
Kuba Jagoda
  • 4,908
  • 2
  • 19
  • 21