If you followed the last exercise, you can see that your code becomes long and confusing quite fast. To avoid that, we can use comments. You can use comments to add hints, explanations or descriptions to your code that will not be executed. If we take the example of the emoji, you can use them to describe what part of the code is responsible to draw the eyes or the mouth of your emoji.
There are two kinds of comments. Single-line comments that are used for shorter comments. You can write them like this:
1
// This is a single-line comment
Everything behind the //
will not be executed by the computer.
Multi-line comments are used for longer comments, for example descriptions. You start them with /*
and you end them with */
.
1
2
3
4
/*
This is a multi-line comment
in JavaScript.
*/
Here you can see my commented emoji:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
My really nice emoji created for the
Foundations of Programming course at
the Jönköping University 2022
*/
// The background of the emoji
strokeWeight(2);
fill(255, 255, 0);
ellipse(150, 150, 200);
// The eyes
fill(255, 255, 255);
ellipse(120, 130, 40);
ellipse(170, 120, 60);
// The pupils
fill(0, 0, 0);
ellipse(130, 130, 10);
ellipse(150, 110, 10);
// The mouth and teeth
fill(255, 255, 255);
rect(90, 170, 120, 40, 20);
line(90, 190, 210, 190);
line(110, 170, 110, 210);
line(130, 170, 130, 210);
line(150, 170, 150, 210);
line(170, 170, 170, 210);
line(190, 170, 190, 210);
Comment out code
You can also use comments to comment out code. Then this code will not be executed. That is useful if you are trying things out and play around. For example, if you want to try different types of eyes on your emoji without deleting them. We will have a look at some examples in the coming chapters.