I've been exploring scope within JavaScript. Sources point out that scope is function-delimited, not block-delimited as in most languages.
I put some display code in some code I'm writing, because some of my functions-within-functions are not clear (to me), and I wanted to see just how the scope works for these.
The big surprise is that in the $.each function within the $.getJSON function the if(){} clause is, evidently, treated as a function. I would have assumed it to be a block.
function displayInfo(nKey) {
if(!nKey) var nKey = 0;
var objFilm = {};
var imgRef;
//iterate through all object properties; display their attributes
// Object.keys() returns an array of all property names
// for most entries, the object is ...film; check first for array of multiple films
jqxhr = $.getJSON('dbMovies.json', function(data) {
var xx = "xx";
$.each(data.disc, function(i, xdata) {
if(xdata.key == nKey) {
objFilm = xdata.film;
var yy = "yy";
imgRef = xdata.img;
return false;
}
console.log("in jqxhr, xx: " + typeof xx); //this shows
console.log("in jqxhr, yy: " + typeof yy); //this does NOT
}); // $.each
})
.done(function() {...}
If if(){} is a function, what is a block?
var foo = if(...) {... }is a flat-out syntax error. it's a keyword. and note that yourif()inside the .each is actually inside a function:function(i,xdata) ...ifisn't a function. What makes you think it's a function?