Before we go deeper into p5, I want to take a moment and discuss “Comments”.
Comments serve two purposes in code;
Let’s talk about the first of these purposes initially.
I am sure you can think of a number of reasons why you may want to include comments in code?
Let’s go over a few reasons why you may want to include comments in your code.
TODO:
“ within your code along with what it is you still need todo. There are even packages from editors, such as Atom, that can show you a list of your remaining TODO’s in a project or simply highlight your TODO’s for you to easily see.Comments are for developers or people only. Computers and processors ignore comments in code. They will literally just skip right over them and proceed to the next statement when trying to compile or process code.
Since computers skip comments when processing code, you can use comments to turn on or off portions of your code. This can be useful for a number of reasons that you will discover over the course of the semester.
For one, it will allow you to try different lines of code in your sketch to compare and see which works better.
They can also be used for debugging, which we will talk more about later. Essentially though, you can use comments to “turn off” portions of code to see if the lines in question are causing your code to break.
Comments are designated slightly different in every language. In JavaScript comments can be written in one of two ways.
In-line comments are designated with two forward slashes. (//
)
Anything placed after these slashes on a line is considered a comment and is ignored by the computer.
Notice in the below example, how the color coding changes to light grey at the slashes and after. This is a visual indication to the developer that the text is “commented out”.
1
2
3
4
5
6
7
8
// This is a comment.
// Everything after the slashes is ignored.
// you can place comments above or below code
// you can also place comments at the end of a line of code
function setup() { // comment
}
With in-line comments, if you wanted to comment out a number of lines of code, you would need to place a set of slashes at the start of each line of code. Sometimes this is impractical. For these situations, you can instead use “block comments”. Block comments are capable of spanning multiple lines of code.
To specify a block comment, you must include a forward slash with an asterisk (/*
), followed an asterisk with a forward slash (*/
). Anything placed between these two symbols is considered a comment and ignored by the computer. (/* This is a block comment */
)
Notice in the below example how the block comment spans multiple lines.
1
2
3
4
5
6
7
8
9
10
11
12
13
/* Block Comment
This just keeps going.
Even code within here is ignored
function setup() {
}
*/
This is now considered code. This line would "throw an error" as the computer does not know what to do with it.