In nodejs 'inspect' acts like a reserved word

javascript, node.js

Solution

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.

Problem

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?

Original source