So far, there has not been any extensive discussion of coding syntax, nor why the computer interprets code in the way it does. Now that our code sketches are getting more involved, this conversation needs to be started.
For the most part, every line of code that we have written between the function blocks for setup()
and draw()
, and the variable declarations outside of these functions, have been individual statements.
A statement in code is a command or instruction for the computer to follow.
For example, calling the create canvas function inside setup()
is a statement.
createCanvas( 400, 200 );
This statement tells the computer to;
This statement is terminated with a semicolon (;
) at the end of the line.
Likewise, when declaring and assigning a variable, like the following;
let myVar = 200;
This is a statement, that tells the computer to;
myVar
200
myVar
This statement, as with the create canvas statement above, is terminated with a semicolon (;
) at the end of the line.
In JavaScript, the semicolon is used to tell a computer that this is the end of a statement.
YOU SHOULD GET IN THE HABIT OF TERMINATING EVERY CODE STATEMENT WITH A SEMICOLON (
;
)
Your code will likely not break if you forget a semicolon at the end of a line. But it is good programming standard for you to follow. For a number of reasons;
YOU would never do the following, but it demonstrates what could happen, and why semicolon’s are important.
It is possible to write multiple statements on a single line of JavaScript code. To do this, you must specify the end of each statement. The following sets the background, declares a variable (der
), declares a variable (duh
), and creates an ellipse dependent on der
and duh
;
background(20); let der=2; let duh=der+100; ellipse(der,duh,der);
Again, YOU should not write code like the above. BUT, it is legal code, and works since the statements are separated with semicolons.
The above would technically also work, if written without semicolons, but on new lines, like;
background( 20 )
let der=2
let duh=der+100
ellipse(der,duh,der)
Again, YOU should not write code like this. BUT, it is legal code. The JavaScript interpreter, will likely execute the code without error, as it will assume that each new line is a new statement.
Of course though, we want to be explicit with the computer, and reduce our chances of it producing unexpected results. That is why the above should actually be written like;
background( 20 );
var der = 2;
var duh = der + 100;
ellipse( der, duh, der );
There are specific instances when we do not want to add semicolon’s. These will be identified to you as we progress this semester. In the meantime, please get in the habit of using semicolon’s after your statements in your current p5 sketch code.