Search code examples
javascriptobject-literal

Puttiing comments in javascript object literals


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;  
    }
  };

Solution

  • 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.