Adding Comments to JavaScript Code
This lesson is part of the Web Programming 1 Course.
Good programmers put notes in their code for themselves and for other programmers. Comments can be used as reminders, they can explain bits of code that may be tricky to understand, and they can actually be used to produce formal documentation for a program.
Comments are not code, and the browser will ignore them when it runs your program. You have to use special characters so that the browser can tell the difference between code and comments.
JavaScript allows you to comment your code in two different ways.
Single Line Comments
To comment out a single line, just start the line with two forward slashes //.
// this is a comment
Multi-Line Comments
If you need to write a long comment that will require more than one line, you can do it like so:
/*
This is a comment that spans
multiple lines
*/
There is one other great use for comments. If you have code that you may not want to keep, but aren't sure yet, you can simply comment it out so that the browser ignores. This is a better option than deleting it, because you find that you do need it, you can simply remove the comments without having to re-write all the code.
// the following code will be ignored by the browser because it's commented out
/*
alert("blah");
console.log("blah");
*/
Generating Documentation from Comments
There is a way of writing comments so that they can be use to generate documentation for your code. We don't need to get into it too deeply at this point, but just to give you an idea of how it works, take a look at the comments that describe a function that we wrote in a previous lesson:
/**
Converts a temperature from celsius to fahrenheit.
@param {number} tempCelsius The temperature in celsius to be converted
@return {number} The temperature in fahrenheit
*/
function convertToFahrenheit(tempCelsius){
const tempFahrenheit = tempCelsius * 9/5 + 32;
return tempFahrenheit;
}
The opening comment includes an extra asterisk, which indicates that this comment should be used in the documentation for your program. There is a specific syntax that you should follow, and in this case you can describe parameters and return values with @param and @return followed by the data type that for each.
If you add comments like this to all of the functions in your program, you can use a tool that will look these comments and turn them into official documentation that might look something like this:
I created this documentation with this online documentation generator.
It's a good skill for a programmer to know how to understand documentation like this to understand how to correctly invoke functions (knowing what to pass in for the parameter(s) and what to expect for the return value).