javascript - var x = x || "default val" not getting set properly if x is defined above it -
javascript - var x = x || "default val" not getting set properly if x is defined above it -
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); // alerts "default val" , not "overriden" });
for reason, x
ending "default val"
, not "overriden"
, tho i'm setting "overriden"
before include script reference myjs.js.
any thought why happening? i'm trying enable hosting page set override variable that's used in included js file, otherwise utilize default val.
what have after variable declaration hoisting applied:
var x; x = 5; $(document).ready(function(){ var x; x = x || "default"; });
it looks @ closest x
, sees it's value undefined
falsy value, x
gets set "default"
. fine if in same scope, because declarations hoisted above assignments so:
var x = 5; var x = x || "default";
is just
var x; x = 5; x = x || "default";
this suggested pointless:
$(document).ready(function(){ x = x || "default"; });
it throw referenceerror
if x
not defined. either check in same scope or like:
$(document).ready(function(){ var x = window.x || "default"; });
invalid property reads don't cause referenceerror
homecoming undefined
instead.
javascript jquery
Comments
Post a Comment