If I use this:
<script>
$(document).ready(function() {
if (window.localStorage.getItem('createTicket')) {
var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
}
});
</script
I see an error in the console:
Uncaught ReferenceError: createTicketInfo is not defined

But if I remove document.ready:
<script>
if (window.localStorage.getItem('createTicket')) {
var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
}
</script>
Everything is ok:

Why?
It's because, in the first example, createTicketInfo is only visible within the callback (function) of ready.
function test() {
var boo = "Hi! I'm boo.";
// ...
console.log(boo); // visible here
}
test();
console.log(boo); // not visible here (even if we call test first)
In the second example, createTicketInfo is not wrapped in a function, thus it is global (visible everywhere).
if(true) {
if(true) {
if(true) {
var foo = "Hi! I'm foo.";
// ...
console.log(foo); // visible here
}
}
}
console.log(foo); // visible here too (because javascript doesn't have block scopes)
Always put in mind that javascript has function scopes, but not block scopes.
Note: As mentioned by @nnnnnn in the comment bellow, ECMAScript 6 introduced a new way of declaring variables using let or const that respect block scopes. So:
if(true) {
let zoo = "Hi! I'm zoo.";
// ...
console.log(zoo); // only visible inside this block
}
console.log(zoo); // not visible here
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