In nodejs 'inspect' acts like a reserved word

In node.js calling console.log on an object that has an element called inspect prints undefined even though it still works as an object. I assume this is because node uses inspect internally to print stuff out.

var thingTwo = {
  num: 1,
  func: function (x) { 2; },
  inspect: function (x) { "hi"; },
};

console.log(thingTwo);  // undefined

To avoid this trap in the future is there a list of other words that break standard functionality?

Cool, this piqued my curiosity and indeed, there is an undocumented feature where an object can provide it's own inspect method. The relevant code in util.js:

function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (value && typeof value.inspect === 'function' &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    return String(value.inspect(recurseTimes));
  }

I.e., it's only when inspect exists and is a function that triggers the behavior.

If an object has an inspect property and it is a function, console.log prints its return value.

$ node
> console.log({ inspect: function() { return 'hi'; } });
hi

If we look at the source, we'll see that there's no way to avoid this behavior. If an object's inspect is a function, console.log will print its return value.


Note that in Node 0.6.x and before, console.log doesn't actually print undefined, it just prints a blank line. You'd only see undefined if you're doing this in the REPL.