Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't document.ready work in this case?

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

enter image description here

But if I remove document.ready:

<script>    
    if (window.localStorage.getItem('createTicket')) {
        var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
    }   
</script>

Everything is ok:
enter image description here

Why?

like image 647
Evgeniy Avatar asked Nov 25 '25 07:11

Evgeniy


1 Answers

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
like image 62
ibrahim mahrir Avatar answered Nov 26 '25 19:11

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!