I was playing around with some JavaScript code and found that when I took my “console.dir” statements out, the results were different. It appeared as if certain properties seemed to become visible after console.dir was called. For example, the below code will print out “undefined” for x1._rgbString, but will print out an actual value for x2._rgbString.
var x1 = MochiKit.Color.Color.fromHexString("#ad3f40");
console.log(x1._rgbString);
var x2 = MochiKit.Color.Color.fromHexString("#ad3f40");
console.dir(x2);
console.log(x2._rgbString);
Full test code here: http://patorjk.com/misc/console-dir-test.htm
If I add in a console.dir(x1) before console.log(x1._rgbString), then console.log(x1._rgbString) will start printing out a value instead of printing out undefined.
Why would calling console.dir on the object effect the value of fields on the object? Does console.dir have side effects or is there something I’m missing here?
*I’m aware that underscores usually mean private, but I was logging this value and was surprised it started showing up as “undefined” when console.dir wasn’t first called.
The reason is that console.dir (and console.log for that matter) calls
toString()on the value you pass to it. That normally would have no side effect, but Mochikit.Color.Color’s toString() in turn callstoRGBString(). And toRGBString() caches its result inthis._rgbString:So, it’s not that the console functions have side effects as such, it’s just that some toString() implementations may have. It’s worth noting that some JS minimizers (including Google Closure Compiler) assume that there are no side effects in toString(), so they may actually do optimizations that will have impact on code that does.
In this case it wouldn’t be a problem, since the side effect is just caching – as long as you don’t use it externally – hence the “private” underscore.