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?
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