Lesson 3.4. Comments in JavaScript

Comments can be written in a JavaScript code. The comments have several uses:

Single line comments

Single line comments start with the syntax //. The text between // and the end of the line is ignored at runtime. Here is an example comment:

// Display Hello World <= This is a single line comment
console.log ('Hello World');

Comments do not necessarily start at the beginning of the line:

const pi = 3.1415;   // This constant defines the value of π

Comment on several lines

Multi-line comments start with /* and end with */. The text between /* and */ is ignored at runtime. Here is an example of a multi-line comment comment:

/* 
The code below allows you to change the first <h1> title

document                    => This is the current document (HTML page)
.getElementsByTagName("h1") => get all the <h1> elements of the page
[0]                         => isolate the first element
.innerHTML                  => is the text (or HTML) contained in the <h1> tag
*/
document.getElementsByTagName("h1")[0].innerHTML= "I replaced the title!"

Exercise

The following HTML code opens a pop-up when the page is loaded. Without deleting it, comment out the pop-up code to prevent it from running. The rest of the code should still run.

<html>
  <head>
  </head>
  <body>
    <h1>CComments in JavaScript</h1>
    <script>
      alert('I know a pop-up that annoys people.');
      console.log ("In the console, it is more discreet.");
    </script>
  </body>
</html>

Quiz

What can the comments be used for?

Check Bravo! A well-commented code is easier to understand. Try again...

Which syntax allows you to write a single line comment?

Check Bravo ! You can also write a single-line comment with /* */. Who can do more, can do less! Try again...

Which propositions are true?

Check Bravo ! The right syntax is /* */. Try again...

See also


Last update : 10/03/2022