JavaScript comments are used to explain the purpose of your code and make it more readable. Comments are not executed as a part of the program; they are solely meant for human developers to understand the code better. The browser simply ignores them.
You can use comments for various purposes, such as:
Tip: A good developer always writes clear comments to explain the why behind complex code logic.
There are two common ways to write comments in JavaScript:
You can start a single-line comment with a double forward slash (//). Everything written after the // until the end of that specific line is treated as a comment.
Syntax:
// This is a single-line comment message
// Defining the first string var string1 = "JavaScript";// Defining the second string var string2 = "TypeScript";
// Printing the combined strings document.write(string1, " and ", string2);
The multi-line comment is extremely useful when you need to comment out multiple lines of code or write a longer, detailed explanation. You can write multi-line comments between the /* and */ symbols.
Syntax:
/* First line of the comment message
The second line of the comment message */
let result = addition(100, 200);
document.write("Result = " + result);
/* This function accepts two values as parameters,
adds them together, and returns the computed result */
function addition(a, b) {
return a + b;
}
In addition to providing information about the code, comments are frequently used during the debugging process to prevent the execution of a particular piece of code.
By commenting out a line or a block of code, you can test how your program runs without it, saving you the hassle of deleting and re-typing it later.
var bool1 = true; var a = 100; var b = 200;// The line below is commented out, so bool1 remains true // bool1 = false;
/* The block below is completely ignored by the browser: a = a + b; b = a - b; a = a - b; */
document.write("bool1 is: " + bool1 + "<br>"); // We can place a comment at the end of a line document.write("a = " + a + ", b = " + b);
Which syntax is used to create a multi-line comment in JavaScript?