JavaScript comments are used to explain and improve the readability of JavaScript code. They can also be used to make notes in your lines of code or to deactivate lines of code without removing them entirely.
A variety of computer languages have the ability to comment on code. The concept behind code commenting is that while your lines of code will be viewed by computers, they will also be viewed by humans; hence it is critical that your code must be easy to comprehend.
Comments let you keep track of your code while programming, as well as take notes that could be useful later on. Furthermore, if you’re working on a team, leaving comments will help make sure that your lines of code are readable by everyone who might have to make a contribution to your work.
Types of Javascript Comments
There are two types of Javascript comments. They are; Single line and Block comments.
- Single line Javascript comments:
Single line JS Comments are shown using two (2) forward slashes (//) which will be written on just a line of code. Every other character after the two forward slashes will be set aside and ignored till the end of that line.
This is a simple example of Single line comment:
// Change heading: document.getElementById("myH").innerHTML = "Techstack First Page"; // Change paragraph: document.getElementById("myP").innerHTML = "Techstack first paragraph.";
2. Block or Multi-line Javascript comments:
Block or Multi-line comments are used to add both single and block comments which makes it the better option. These block comments are written with opening and closing tags, and they allow commenting that spans across various lines. Multi-line or Block comments end with */ and begin with /*.
/* The code below will alter the heading with id = "myH" as well as the paragraph with id = "myP" in the web page: */ document.getElementById("myH").innerHTML = "Techstack First Page"; document.getElementById("myP").innerHTML = "Techstack first paragraph.";
Advantages of Javascript comments
- They allow code to be easier to read and understand.
- It makes it easy when you’re working in a group for other group members to edit and modify your code.
- To deactivate lines of code that aren’t needed anymore without completely removing them.