skip to Main Content

I have something in my html:

<script>
testvar = "mytest";
</script>
<script src="index.js" type="module"/>

Since some html might not declare the testvar at all.
I try to make my script more robust by adding following in index.js:

testvar ??= "default";

However, this does not seem to work, it still raise testvar is not defined in latest chrome.

if I do:

let testvar;
testvar ??= "default";

It does not have error, but of course, the global testvar is not take into account this time. It will always be default.

I wonder, what is the correct way to do this, or there is no way to do things like this?

2

Answers


  1. You can’t use ??= to declare a global variable – you can only use it to set existing variables that are set to undefined.

    You can instead do globalThis.testvar ??= "default", which will work because you’re setting a property rather than declaring a globally scoped variable.

    This approach will still allow you to later access it as simply testvar.

    globalThis.testvar ??= "default"
    
    console.log(testvar)

    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

    Login or Signup to reply.
  2. Top-level variables that are created in javascript (running in a browser) become properties of the window object.

    That means you can access it everywhere with window.testvar.

    You can also assign it with the ??= operator.

    Demo:

    // Here we can't use only `testvar` yet, it must be prefixed:
    console.log(window.testvar ?? "-- HAS NO VALUE --");
    
    window.testvar ??= "default";
    
    // Now we can use it without the prefix:
    console.log(testvar);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search