Writing Comments and Readable Code
Introduction
Welcome back to Writing and Running Your First JavaScript Programs! We are now stepping into the second lesson of the course, so we are officially building momentum.
In the previous lesson, we wrote our very first console.log lines and watched JavaScript display text and numbers on the screen. Those programs were short and easy to follow at a glance, but real programs grow longer very quickly, and our future selves - or a teammate - will thank us for leaving helpful notes along the way.
In this lesson, we will learn how to:
- Write comments with
//to explain what our code does. - Use a comment to temporarily switch off a line of code.
- Keep our programs tidy with blank lines and one instruction per line.
- Leave ourselves a
TODOnote marking work still to be done.
By the end, we will have a short greeting program that reads almost like a friendly note.
What Is a Comment?
A comment is a line of text inside our program that is meant for people, not for the computer. When JavaScript runs the program, it skips every comment completely, as if the line were not there at all.
In JavaScript, a comment starts with two forward slashes, //. Everything from those slashes to the end of the line is a comment. There is no closing mark to remember: the line simply ends, and so does the comment.
Comments are how we explain why the code is there. The code itself already says what happens; a good comment says what it is for.
There is also a second form for a note that needs more than one line. A block comment starts with /* and ends with */, and JavaScript ignores everything between the two marks, even across several lines:
We will use // for everything in this course, since one short note per line is all our programs need, but it is worth recognising /* and */ when we meet them in other people's code.
Writing a Note Above the Code
The most common place for a comment is on its own line, directly above the code it describes. Here is a greeting for the Corner Cafe with a note above it:
When we run this, only the greeting appears:
The comment line produced nothing, because JavaScript never looked at it. It is there purely for whoever reads the file next - which is very often us, a week later, wondering what we were thinking.
