skip to Main Content

if I console.log an object, it outputs all the key/value pairs as well as its methods.

const obj = {
    name: "Mike",
    add : function (a, b){
       return a + b
    }
}

console.log(obj)

but the error object in try…catch block, console.log(err) outputs message something like "reference error: variable is not defined"

try {
   variable
}
catch(err) {
   console.log(err)
}

Why does it outputs message, instead of its key/value pairs and methods?

2

Answers


  1. The underlying conversion of arguments into console messages for console.log() does not have to always print out the key-value pairs of object and varies from environment to environment.

    For example, the console object in NodeJS uses util.format() to perform the conversion, and that in turn calls util.inspect() to format object, which treats Error objects differently to normal objects. I’m not sure about the specifics for other browsers, however, but they probably also treat Error objects differently as well to aid debugging.

    Does this answer your question?

    Login or Signup to reply.
  2. When catching an error using a try...catch block, you’re dealing with an instance of one the error objects (name, message, stack*). The error object is created with the specific error information, including the name and message properties, and possibly the stack property.

    The err object is an instance of ReferenceError, and it contains a message property that describes the error message, which is ReferenceError: variable is not defined. This is what gets logged when you call console.log(err).

    If you want to access other properties and methods of error objects, you can do so explicitly. For example, you can log the name and stack properties like this:

    console.log(err.name);
    console.log(err.stack);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search