HTML:
<script type="text/javascript">
var x = "overriden";
</script>
<script src="myjs.js"></script>
myjs.js:
$(document).ready(function(){
var x = x || "default val";
alert(x); // this alerts "default val" and not "overriden"
});
For some reason, x is ending up as "default val" and not "overriden", even tho initially I’m setting it to "overriden" before I even include the script reference to myjs.js.
Any idea as to why this is happening? I’m trying to enable the hosting page to set an override for a variable that’s used in an included js file, otherwise use the default val.
What you have after variable declaration hoisting is applied:
It looks at the closest
xand sees it’s value isundefinedwhich is a falsy value, soxgets set to"default".You would be fine if they were in the same scope, because the declarations are always hoisted above assignments so:
Is actually just
This was suggested which is completely pointless:
It will throw a
ReferenceErrorifxis not defined.So either do the check in the same scope or do something like:
Invalid property reads don’t cause a
ReferenceErrorbut just returnundefinedinstead.