2

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?

ckersch
  • 7,507
  • 2
  • 37
  • 44
  • 2
    If the variable is not references from your closure, V8 takes the liberty to garbage-collect it (and it will be referenced when you add the log statement). See [How are closures and scopes represented at run time in JavaScript](http://stackoverflow.com/questions/5368048/how-are-closures-and-scopes-represented-at-run-time-in-javascript) or [garbage collection with node.js](http://stackoverflow.com/q/5326300/1048572) (Not sure whether there's a better duplicate) – Bergi Mar 19 '13 at 17:03
  • 1
    Ah, maybe better duplicate of [Debugging Revealing Module Pattern: functions not in scope until called?](http://stackoverflow.com/q/14853938/1048572) – Bergi Mar 19 '13 at 17:06

0 Answers0