I want to use a local variable as a global variable and I was told the way to do so is to create the variable outside the function, like this:
var foo = null;
function bar() {
foo = 3;
}
console.log(foo);
However the foo logs null, instead of 3. This is the simplest example I could think of, but mainly I want to be able to use the data from a variable I created in a function throughout my whole script.
What am I doing wrong?
Same question in an Ajax request :
var status = null;
.ajax({
url: myUrl,
success: function (data) {
status = data.status; //returns a string
console.log(status); // it works, I get the string
},
dataType: 'jsonp'
});
console.log(status); // still null