In the first week of looking at p5, the idea of functions were presented. A slightly updated list of what was presented follows;
A function is a;
Calling a function requires;
()
, without a space between them and the piece of text.
nameOfFunction()
A function;
The Mozilla Developer Network defines functions as;
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value.
At this point in the semester, you have presumably gotten quite good at using built-in functions provided by p5 or more broadly JavaScript.
You have also hopefully started to acquire the ability to look up and find functions. You might look up functions when you need to do something and do not know if there already exists a function to do it. Or you may look up a function when you know one exists, but cannot remember the name of it. This is the process of looking through the p5 reference page or the JavaScript Documentation Guide. These searches will allow you to discover additional functions that you may not have known existed.
This is a skill you will continue to develop throughout your coding work. It is important to be able to look up documentation, and find functions or techniques that allow you to do what it is you want/need to do.
You are able to do this, because you now understand enough of the basics of JavaScript that you can see a new function, and through reading its documentation, figure out what it will do. This is also possible, because you know enough about JavaScript now to understand generally how all functions are syntactically implemented in the language. That is, you know how to write a function into your code; provide that function with input parameters; and capture/utilize any returned data from that function.
But what do you do if you cannot find a function that does exactly what you are trying to do?
JavaScript, and almost every other language, allows you to define your own functions to be used in code in the ways you need.
There are many reasons why you might define and use your own functions;
We are going to look very specifically at how to define and use your own functions over the next few pages. But, just so you know, you have been defining your own functions every week this entire semester already. The process of writing the setup()
and draw()
functions is function definition. By writing these two functions every week, you are providing functions that the p5 interpreter can call/use, which do something. Most likely, you have been writing these functions so that something is drawn, moved, or interacted with.
Furthermore, as you will see, the syntax for defining these functions is the same syntax used to define all function within JavaScript. This means you are likely already comfortable with the new syntax we will look at as well this week.