Search code examples
javascriptarrayssetvalue

Setting value for global array in Javascript doesn't work


I am trying to set a global variable via function call based on the specified options/values of the function call. Here's my code:

    let g_Pl = [];

    function prepare() {
        let s = 0;

            s = 1;
            g_Pl[s] = 5;

            s = 2;
            g_Pl[s] = 8;

            s = 3;
            g_Pl[s] = 10;
        }

    function getInfo(s,map,pl) {
        switch (map) {
            case "test":
                pl = g_Pl[s];
            break;
        }
    }

function test() {
    let local_Pl;

    getInfo(1, "test", local_Pl)

    console.log(local_Pl);
}

prepare();
test();

But the console output is "undefined" and I am wondering why? local_Pl is supposed to be set a value from getInfo which has to be "5" based on the parameters in prepare():

s = 1;
g_Pl[s] = 5;

Why it doesn't work ?


Solution

  • You are using pl and local_Pl as an out parameter aka pass by reference parameter or ByRef, but JavaScript doesn't support that functionality. You should instead return the result, like so:

    function getInfo(s, map) {
        switch (map) {
            case "test":
                return g_Pl[s];
        }
    }
    
    function test() {
        let local_Pl = getInfo(1, "test");
        console.log(local_Pl);
    }
    

    If you need to return something and also have an out parameter then you can just create an object to contain both and return that object.

    function getInfo(s, map) {
        var element;
        switch (map) {
            case "test":
                element = g_Pl[s];
                break;
        }
        return { found: !!element, pl: element };
    }
    
    function test() {
        let result = getInfo(1, "test");
        if (result.found) console.log(result.pl);
    }