Writing Comments In JavaScript
In this short lesson you will learn about adding code comments in JavaScript.
By the end you will understand how comments can help to improve your experience when writing code, as well as the experience of others reading it.
We will cover:
What is a comment?
Comments enable you to add extra information about your code without impacting the execution.
You can add any notes that you want and nothing will be outputted to the console or the end user.
Adding a comment
To add a comment, type two forward slash /
characters followed by the note you'd like to add.
In the following example a comment has been added above a console.log()
statement to explain what it is doing:
// Output a statement with console.log()
console.log('Hello, Middle Earth!');
This is known as a single-line comment.
When this code is executed, notice that the console.log()
statement is outputted to the terminal and prints the line 'Hello, Middle Earth!'
, but the comment is not!
Multi-line comments
As well as single-line comments, you can also create comments that span multiple lines.
You can do this using a single forward slash followed by an asterisk: /*
. This 'opens' the comment area, much like an opening tag in HTML.
You then need to close the comments with an asterisk and forward slash: */
. Any comments need to be added between these opening and closing pairs.
This is very similar to the structure of comments in CSS, so you may already be familiar with this syntax.
The following is an example of a multi-line comment:
/*
This is a multi-line comment.
It spans multiple lines!
*/
While it's possible to achieve this with a double forward slash //
on each line, often it's cleaner to use the multi-line syntax.
Shortcuts
You can use a keyboard shortcut to convert a single line to a comment e.g. Cmd + / on Mac or Ctrl + / on Windows.
You can also use this to comment out existing code. This can be helpful if you want to quickly disable lines of code when debugging or testing, for example.
Try placing the cursor on the line that contains the console.log()
statement and use the shortcut to comment it out.
You can then repeat this shortcut to bring it back - much easier!
Making notes
Remember that all comments will be ignored by the JavaScript compiler.
This means that you are free to add anything that you'd like that may aid your understanding when returning to the code at a later time.
It can also be very helpful for others to read informative comments when working on a shared project.
Summary
As you can see, commenting your code can be very useful! In this lesson you've learned what code comments are, how to write them, as well as their benefits.
Writing informative comments not only benefits you, but anyone else who reads your code, also!
Next steps
Now that you have set up your coding environment, can execute code, and understand how to add comments to your code, you're ready to delve deeper into the JavaScript language!