The Importance of Comments and Programming Grammar

Learn about adding comments and programming grammar with some JavaScript examples.

In this chapter, we’re going to look at some of the basics of programming and write some more programs.

Comments

The first task on our journey to becoming a programmer is learning how to “comment” our code. Comments in programming are similar to marginal notes in a book: they’re notes that explain the purpose and rationale of the code. This may seem a strange place to start, because comments are ignored by the programming language. They don’t do anything. Despite this, comments are extremely important. Well-commented code is the hallmark of a skilled programmer. Comments make it easier for anybody reading our code to understand what’s going on—including us! We’ll be thanking ourselves for commenting the code when we come back to read it after a few weeks. We don’t need to write an essay, though, just enough so that it’s clear what the code is supposed to do.

How to add comments varies between programming languages. In JavaScript, there are two types of comment:

  • Single-line comments start with // and finish at the end of the line:
// this is a short comment
  • Multi-line comments start with /* and finishing with */ :
/* This is a longer comment
anything here will be ignored
This is a useful place to put notes
*/

It’s good practice to write comments in our code, but make sure that the comments are useful and not just describing what’s fairly obvious from the code itself. For example, the following comment doesn’t really add anything that isn’t obvious from the code itself:

// log the message to the console
console.log(message);

It’s useful to think of comments as notes to our future selves, to remind us about what our thinking process was when we wrote that particular piece of code. For example, here’s a comment explaining that the code is activated by a user clicking the left arrow key:

// user has clicked on the left arrow key so move left
character.style.left = left - speed + 'px';

Get hands-on with 1200+ tech skills courses.