If I declare a global variable right after a script tag, is it safe to access this variable in a function called in document ready?
<script type="text/javascript">
var bar = "foo";
$(document).ready(function(){
callBar()
});
function callBar(){
alert(bar);
// will I crash?
}
</script>
what then if I do this:
<script type="text/javascript">
$(document).ready(function(){
callBar()
});
function callBar(){
alert(bar);
// will I crash?
}
var bar = "foo";
</script>
is it safe to access this variable in a function called in document ready
Yes. The variable is declared (added as a binding to the variable environment of the execution context) as a very early step of executing that script. (Note that it doesn't actually get assigned a value until the assignment statement is reached during parsing. This is commonly referred to as "hoisting" but will not affect your example).
Since script execution is synchronous (the browser will stop rendering until it's finished parsing and executing the script element), the DOM ready event will not fire until that execution is complete.
Edit (question was updated)
what then if I do this...
As described above, the variable declaration will be hoisted to the top of the scope in which it appears. Your second example is effectively interpreted as follows:
// Declarations (both function and variable) are hoisted
var bar;
function callBar() {
alert(bar);
}
$(document).ready(function () {
callBar();
});
bar = "foo";
Those declarations are therefore available throughout the entire scope. The ready event handler will be executed some time later, and has access to those declarations (since they appeared in the same scope as it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With