Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - where are the name and message properties of Error object?

Trying to understand why the two cross-browser properties of Javascript Error object, namely "name" and "message", can't be found using the "for ... in" method

// error code
...
}catch( err ){

  // in FF this lists 3 properties for fileName, lineNumber and columnNumber...
  // but NOT name or message!
  for(var propertyName in err) {
    $( '#diags' ).append( 'err property: ' + propertyName + ', 
       value: ' + err[ propertyName ] + '<br>' );
  }
  // this line prints fine:
  $( '#diags' ).append( 'Error - name:' + err.name + ', message: ' + err.message + '<br>' );
}

Edit

I am asked what is name and message. These are properties (are they though?) which all Errors have in any browser... so in the above code I have added an extra line of code which shows that these "attributes" or whatever they are print fine

Edit2

Following Mati's helpful answer I did a bit of searching. This seems to answer the "inspection" question: Is it possible to get the non-enumerable inherited property names of an object?

like image 935
mike rodent Avatar asked Mar 27 '13 09:03

mike rodent


1 Answers

A for...in loop does not iterate over non–enumerable properties.

var e = new Error('a');

console.log(e.propertyIsEnumerable('name'));
console.log(e.propertyIsEnumerable('message'));
console.log(e.propertyIsEnumerable('fileName'));
console.log(e.propertyIsEnumerable('lineNumber'));
console.log(e.propertyIsEnumerable('columnNumber'));

for(var prop in e)
{
    console.log(prop + ': ' + e[prop]);
}

Output

false
false
true
true
true
fileName: index.html
lineNumber: 25
columnNumber: 0
like image 73
Mati Avatar answered Nov 07 '22 09:11

Mati