2

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.

a43nigam
  • 190
  • 1
  • 10
  • I'm not sure what you were expecting. you are declaring a new variable "postalcode" that is local, so it is not going to have anything to do with the global variable – Rick Feb 07 '21 at 23:34

2 Answers2

2

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())
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Your snippet in StackOverflow works, but it is not working for my website. I am using Wix Velo to make my website, maybe there is an issue with Wix? – a43nigam Feb 08 '21 at 19:09
  • Wix may be limiting your JavaScript execution, but It's very difficult to know exactly what's going on with your code remotely. – Pedro Lobito Feb 08 '21 at 23:51
1

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;
}
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
  • If you would explain why this works (he's declaring a new local variable with the same name that shadows the global) it would significantly improve this answer. A reference to how JS treats variables would be even better :) – Tibrogargan Feb 07 '21 at 23:31