How to add comments in javascript

Published: May 02, 2018

DMCA.com Protection Status

Let's consider a simple html page with some javascript inside:

<!DOCTYPE html>
<html lang="en">
<body>

<h2>Test JavaScript Comments </h2>

<p id="demo">Bonjour tout le monde !</p>

<button type="button" onclick="change_txt_function()">Click</button>

<script>
function change_txt_function() {
    document.getElementById("demo").innerHTML = "Hello World !";
}
</script>

</body>
</html>

Inline Comment

To add a comment for a given line, usd the following syntax

// comment here

example

function change_txt_function() {
    document.getElementById("demo").innerHTML = "Hello World !"; // Mon Commentaire
}

To comment a full line of code

function change_txt_function() {
    // document.getElementById("demo").innerHTML = "Hello World !";
}

Multiples Lines Comments

To add comments on multiple lines:

/*
comment line 1
comment line 2
comment line 3
*/

example 1 (add a comment on multiple lines)

<script>
function change_txt_function() {
    document.getElementById("demo").innerHTML = "Hello World !";
}
/*
comment here
comment here
*/
</script>

example 2

<script>
/*
function change_txt_function() {
    document.getElementById("demo").innerHTML = "Hello World !";
}
*/
</script>

References