While working on a JavaScript application, I came across something unexpected while using the Chrome developer tools. I have, within a function, the following block of code:
var b = bins + 1,
selectValues = [],
selectedPoints = [],
n = numVals;
while(b--){selectValues.push(0)};
//Main selection iterator
if (range_min == range_max){
mainSVG.selectAll(".sim-ui-scatter-points")
.each(function(){
d3.select(this).call(addClass,["foo"]);
d3.select(this).call(removeClass,["bar","foobar"])
});
} else {
do some other stuff
});
}
Planning on adding some functionaility with the variable n
that would occur for each item inside of the .each
statement, I put a breakpoint inside the .each
statement using the Chrome debugger, and then asked for n
in the console while the browser was paused on the breakpoint, and got back ReferenceError: n is not defined
. However, if add a console.log(n)
to my code, as follows:
//Main selection iterator
if (range_min == range_max){
mainSVG.selectAll(".sim-ui-scatter-points")
.each(function(){
console.log(n)
d3.select(this).call(addClass,["foo"]);
d3.select(this).call(removeClass,["bar","foobar"])
});
} else {
do some other stuff
});
}
Not only does the code properly return n
to the console, but I can ask for n
in my console in the Chrome debugger, using a breakpoint on the same line as I was using before and get a correct value instead of a reference error. Why does this happen?