Javascript scope variable (global/local) -


i want use local variable global variable , told way create variable outside function, this:

        var foo = null;          function bar() {             foo = 3;         }          console.log(foo); 

however foo logs null, instead of 3. simplest example think of, want able use data variable created in function throughout whole script.

what doing wrong?


same question in ajax request :

var status = null;  .ajax({   url: myurl,    success: function (data) {     status = data.status; //returns string     console.log(status); // works, string   },    datatype: 'jsonp'  });  console.log(status); // still null 

you need call function first this.

    var foo = null;      function bar() {         foo = 3;     }      bar();     console.log(foo); 

your best bet here call function logs data after ajax runs. in example created function called logit() called in ajax request state.

var status = null;  $.ajax({   url: myurl,    success: function (data) {     status = data.status; //returns string     console.log(status); // works, string     logit();   },    datatype: 'jsonp'  });  function logit(){     console.log("logit(): " + status); } 

the reason getting null because order code running:

  1. sets status null
  2. saves ajax memory run when requests completes doesn't run yet
  3. logs status still null because success callback hasn't run yet
  4. the ajax request completes , runs success callback
  5. status set data.status

Comments