Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;  
    }
  };
like image 797
andco42 Avatar asked May 25 '15 13:05

andco42


People also ask

What does object literal mean in JavaScript?

An Object is a special type of value in JavaScript that can have connections with other values. An Object Literal is an object value that you literally write in your program/app. An Object Literal usually consists of a list of comma-separated name-value pairs ( property:value ), wrapped inside curly braces {} .

How do you comment out an alert in JavaScript?

Single line Javascript comments start with two forward slashes (//). All text after the two forward slashes until the end of a line makes up a comment, even when there are forward slashes in the commented text.

What are enhanced object literals in JavaScript?

February 8, 2021. JavaScript. JavaScript introduced a ton of new concepts with ES6, but one feature that is often overlooked is the enhancements to object literals. With these enhancements you can write code to create objects that is easier to read and more concise.


1 Answers

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.

like image 96
Robert Rossmann Avatar answered Oct 30 '22 02:10

Robert Rossmann