Thu. Dec 5th, 2024

JavaScript Comments

JavaScript comments can be used to make the code more readable.


JavaScript Comments

Comments will not be executed by JavaScript.

Comments can be added to explain the JavaScript, or to make the code more readable.

Single line comments start with //.

The following example uses single line comments to explain the code:

Example

// Write to a heading:
document.getElementById(“myH1″).innerHTML=”Welcome to my Homepage”;
// Write to a paragraph:
document.getElementById(“myP”).innerHTML=”This is my first paragraph.”;

 


JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.

The following example uses a multi line comment to explain the code:

Example

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById(“myH1″).innerHTML=”Welcome to my Homepage”;
document.getElementById(“myP”).innerHTML=”This is my first paragraph.”;

 


Using Comments to Prevent Execution

In the following example the comment is used to prevent the execution of one of the codelines (can be suitable for debugging):

Example

//document.getElementById(“myH1″).innerHTML=”Welcome to my Homepage”;
document.getElementById(“myP”).innerHTML=”This is my first paragraph.”;

In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):

Example

/*
document.getElementById(“myH1″).innerHTML=”Welcome to my Homepage”;
document.getElementById(“myP”).innerHTML=”This is my first paragraph.”;
*/

 


Using Comments at the End of a Line

In the following example the comment is placed at the end of a code line:

Example

var x=5;    // declare x and assign 5 to it
var y=x+2;  // declare y and assign x+2 to it

369,515 total views, 1 views today

Leave a Reply