Thursday, March 2, 2023

debugger beware! objects in console.log() are dynamic

TL/DR: if you blast an object to console.log(), like an array or map, that is likely to be a "live" display of the value of the array, not what was present at the moment you called console.log. One work around is to use console.log(JSON.stringify(thingy, null, ' '));

One of the silver linings of being an old gray beard is this kind of problem just made me stumble for a minute, but then the "wait-a-minute" factor kicked in and I came up with a workaround...

So at work I'm doing a project that's a wrapper for google chart - there was some code here that read values from a table, and I console.log() the results.

this.sourceData = this.parseData(sourceTable,calculateAsPercentage);
console.log(this.sourceData);
let data = google.visualization.arrayToDataTable(this.sourceData);

The thing is when I did some further log() of what was becoming the return value of parseData() inside that function, it looked like the "header" data was being generated and pushed onto the array, but then it disappeared. 

But then I figured out something in Google chart (or maybe processing we do, I dunno) was consuming the first entry with the header data, probably array.pop().) But console.log was always showing me the final version, not the snapshot of what it was at the moment the function was called.

So I realized JSON.stringify() (with the usual (thing, null, ' ') to format it properly ... how many times have I typed that null, ' ' ...) would give me the snapshot in time" I was actually thinking of:

this.sourceData = this.parseData(sourceTable,calculateAsPercentage);
console.log(JSON.stringify(this.sourceData, null,' '));
let data = google.visualization.arrayToDataTable(this.sourceData);

BONUS: remember if you are dumping a regular variable to console and want to see it labeled with its name you can stuff it in a map-like object, just two characters more:
console.log({variableName});

No comments:

Post a Comment