0

I have such code:

<body>
  <script>
    window.nix = window.nix || {} ;
    nix.falkorCache = 1;
   </script>
...

I want to get nix variable with jQuery.

How can I access it?

4
  • 2
    How are you trying to access it and where ? Please share the code. Commented Jun 22, 2017 at 14:44
  • Please provide more context. This sounds like a very basic JavaScript question which you already know the answer to (access variable using nix or window.nix), there is nothing jquery-specific about it. Commented Jun 22, 2017 at 14:50
  • Guys, when I am trying to access window.nix.falkorCache I see Cannot read property 'falkorCache' of undefined Commented Jun 22, 2017 at 15:02
  • Updated the question. The nix.falkorCache creates after the page load. Can it be the problem with trying to access it? Commented Jun 22, 2017 at 15:04

1 Answer 1

1

As you wrote it, it should work. Anything assigned to window can be accessed as if it were a top-level value, i.e.,:

console.log(nix.falkorCache); // should work

If it's telling your that nix is undefined, the most likely culprit is that you are trying to access it before it is there.

In your HTML, that segment of code should be above any code that tries to access it, i.e.:

<body>
  <script>
    console.log(nix.falkorCache); // bad
  </script>
  <script>
    window.nix = window.nix || {};
    nix.falkorCache = 1;
  </script>
  <script>
    console.log(nix.falkorCache); // good
  </script>

That's the most likely culprit for your problem is just having it in the wrong order. If you're pulling in a <script> tag, you should put it at the bottom of your body element.

If that doesn't work, a few less likely culprits are:

  • Ensure you aren't accidentally setting nix to null or undefined in between the two.
  • Ensure you aren't trying to run the other code in an <iframe> or something.
  • Ensure that you don't just have a simple typo somewhere.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But the order is fine. The only problem that window.nix = window.nix || {}; nix.falkorCache = 1; creates after the page load. Could it be the reason why the variable is not accecable?
@KirMazur I'm not sure what you mean by after the page load. If your page refreshes, all data is lost and it all has to be created. Otherwise, it's all about the order. If it is created after it is tried to access, that's no good. Can you update your answer with a more complete example of your call?

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.