7

Is it possible to put comments within javascript object literals? The example below works for me in Firefox, but I cannot find any clear documentation on this. Also, all the examples I look at seem to avoid comments in object literals.

  var o = {
    p1: 2,                 // a comment about p1

    /* A comment about function f1 */
    f1: function() { 
      return 3;  
    }
  };
andco42
  • 123
  • 2
  • 4

2 Answers2

11

Comments can be placed almost anywhere in JavaScript - they are ignored by the parser. See MDN for more info about comments.

Some examples...

function test (/* comment where arguments are usually listed */) {}
var obj = /* comment after assignment operator? Why not */ {}
var obj = { prop/* possible, but please don't do this */: 'val' }

Note that the above examples are not really a good practice - I have included them here only to show that it is possible to put comments on almost any place in JavaScript code.

The rule of thumb is: If you remove all comments and the result is a valid JavaScript, then you can put a comment there.

It is also important to distinguish JavaScript and JSON - while JSON does have JavaScript in its name, it has nothing to do with JavaScript syntax as such. And comments in JSON are not allowed.

Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73
3

Yes, you can. There's no reason not to. JSON doesn't allow it though, but don't get confused between JS and JSON.

Scimonster
  • 32,893
  • 9
  • 77
  • 89