0

I'm having a problem with a window level variable.

When I save data in that variable and try to read that data from it, it gives me undefined.

The following is the code:

window.cart;

function save(name, sku)
{
    window.cart = "sku: "+sku+", nombre: "+name;
};

function read()
{
    console.log(window.cart);
}
3
  • It works fine in the fiddle: jsfiddle.net/wkrsqar4 Commented Oct 6, 2017 at 22:20
  • Please provide a minimal reproducible example. Commented Oct 6, 2017 at 22:20
  • 1
    Window.cart is declared and value is not assigned to that and I don't see function save call in your script ,default value of variable in javascript is undefined Commented Oct 6, 2017 at 22:21

1 Answer 1

1

You need to call your function if you want to access to them and add a onload event to call this when windows body are loaded.

    function save(name, sku)
    {
        window.cart = "sku: "+sku+", nombre: "+name;
    };

    function read()
    {
        console.log(window.cart);
    }

    document.body.onload = function(){
     
      save(20, 'sku_new');
      read();
  
    }

Sign up to request clarification or add additional context in comments.

1 Comment

document.body.onload is completely unnecessary since the code doesn't access the DOM in any way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.