Not able to change value of Global var from inside function

Viewed 61

I tried using this solution but it didn't work for me. In my case I am trying to save a variable using 1 function and call it from another

var postalcode = "code didn't change";

export function save_postal_code(code) {
        var localcode = code
        let postalcode = localcode;
        console.log(code);
}

export function get_postal_code() {
        console.log(postalcode);
        return postalcode;
}

The save_postal_code function logs the correct value, but the get_postal_code function doesn't. I don't know what I am doing wrong.

2 Answers

You're redeclaring postalcode inside save_postal_code() instead of updating its value.
The code needs further revision, but that's outside the scope of this answer.
To have postalcode updated inside save_postal_code(), try:

var postalcode = "code didn't change";

function save_postal_code(code) {
    let localcode = code
    postalcode = localcode;
}

function get_postal_code() {
    return postalcode;
}

save_postal_code("123")
console.log(get_postal_code())

This happens because you're instantiating the variable again using the let keyword (making a more immediate local variable with the same name)

removing the let keyword should fix your issue

var postalcode = "code didn't change";

export function save_postal_code(code) {
        var localcode = code
        postalcode = localcode;
        console.log(code);
}

export function get_postal_code() {
        console.log(postalcode);
        return postalcode;
}
Related