There are two ways you can comment out the code in JavaScript, and they are:
- Single line comment
- Multiple line comment
Let’s take a look at what each of these does:
1. Single line comment
A single-line comment is a type of comment that will create one line of comment. You can do this by adding double forward slashes //
at the start of the JavaScript code. Any code between //
and the end of the statement will be ignored by JavaScript.
// this is one line of comment
A single-line comment is used when you want to comment out one line of code, or add a short description of what the code does.
Example uses of a single-line comment
Example 1: Describing what the code does.
// This function will change the text color to red on button click
function turnRed() {
document.getElementById("exampleText").style.color = "red";
}
Example 2: Commenting out one line of code.
function turnRed() {
document.getElementById("exampleText").style.color = "red";
// console.log("Red button is clicked!"); <-- this code is commented out
}
2. Multiple line comment
A multiple-line comment is a type of comment that will create multiple lines of comment. You can do this by adding a forward slash with an asterisk /*
at the start and then an asterisk with a forward slash */
at the end of the JavaScript code. Any code between /*
and */
will be ignored by JavaScript.
/**
* This is a multiple line comment
* You use this when commenting out a large line of JavaScript code
* You can also use it when giving a long description of what your code does
*/
A multiple-line comment is used when you want to comment out a large line of code, or add extra information so other people can understand what your code does or why it is used.
Example uses of multiple line comment
Example 1: Commenting out multiple lines of code.
function turnRed() {
document.getElementById("exampleText").style.color = "red";
}
/*
function turnBlue() {
document.getElementById("exampleText").style.color = "blue";
}
function turnYellow() {
document.getElementById("exampleText").style.color = "yellow";
}
*/
Example 2: Using multiple line comment to give a long explanation of what the code does or why it is used.
/**
* getElementById is used instead of querySelector because the querySelector
* is not fully supported on Internet Explorer 8, and some of our biggest clients still
* rely on this browser. To ensure that our feature works well on all browsers, we have
* to use getElementById.
*/
function turnRed() {
document.getElementById("exampleText").style.color = "red";
}
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript