Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get value of variable that has been optimized out?

Some variables can be "optimized out" during Javascript execution. Thus values of such variables are not available for inspection while debugging (User documentation). Variables view shows (optimized away) message and console throws following error if the variable is tried to be evaluated:

Error: variable has been optimized out

Is there any way to enforce evaluation of such variable or disable this optimization in Firefox?

like image 273
czerny Avatar asked Jul 19 '15 16:07

czerny


2 Answers

Use the variable in a way that prevents this optimisation.

function NOP() {}

// then in the optimised code

    NOP(myvar);
    // debugging here should now show `myvar`
like image 122
Paul S. Avatar answered Sep 20 '22 05:09

Paul S.


When a variable has been "optimized away," it just means that it's not being modified in the context of the current scope. Hence, the JavaScript engine has done some optimization magic and stashed that variable out of the way for the time being. For example, say you're using lodash to iterate over a collection of some kind.

var parentThingy = [];
var childThingy = [];
_.each (collectionThingy, function(data){

    // parentThingy is not being modified inside this callback
    // so it will be "optimized away" while you are inside this
    // function scope.

    var transformed;
    if (data.someFlag) {
        transformed = transformDataSomehow(data);
    }

    // childThingy is being modified, so you will be able to
    // see its value in the debugger.

    if (transformed) {
        childThingy.push(transformed);
    }
});

// Now that you've exited the callback scope, you will be able to see
// the value of parentThingy again.

if (childThingy.length > 1){
   parentThingy.push(childThingy);
}

You could use the NOP suggestion to force parentThingy to be visible in the callback scope, but since you're not modifying parentThingy inside that callback, you don't need to see it. It hasn't changed and won't change. It's not relevant to the code you're currently debugging. Once you've exited the callback's scope parentThingy will be visible to the debugger again.

FYI: this isn't a Firefox thing. Chrome does the same thing, it just uses different verbiage to indicate the variable is irrelevant to the current scope.

like image 37
SeanH Avatar answered Sep 17 '22 05:09

SeanH