About functions
A function, in our context, is essentially a way of references a set of instructions, without having to write them all out again.
An analogy: Someone says “clean your room”, that means do a whole bunch of other things (i.e. pick up cloths off floor; change bed sheets; remove old coffee cups). CleanYourRoom()
is interpreted by you to mean do all those things.
1
2
3
4
5
function CleanYourRoom() {
pick up clothes
change bed sheets
remove old coffee cups
}
So, we can write functions (i.e. a list of commands) for the program to execute without having to write out each command over and over.
To create a function in javascript, all you need you to do is add some parenthesis after the name, then enclose the instructions with curly brackets.
1
2
3
function myFunction() {
instructions
}
Here’s a simple function, called makeSomeShapes()
written in a p5 sketch that makes a few shapes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function setup() {
}
function draw() {
//call our function
makeSomeShapes();
}
function makeSomeShapes() {
fill('red');
ellipse(50,50,20,20);
fill('blue');
ellipse(20,10,10,10);
}
We can also pass the function an argument, by enclosing a variable inside the parenthesis part. In this example, I’ll pass the makeSomeShapes()
function a variable called dr
. We’ll use this to change the diameter of the ellipse every frame. You’ll note in the definition of the function, I called it radiusChanger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function setup() {
dr = 0;
}
function draw() {
background(255);
makeSomeShapes(dr);
//dr increases by a little bit, each frame
dr = dr + .05;
}
function makeSomeShapes(radiusChanger) {
fill('blue');
ellipse(50,50,20*sin(radiusChanger),20*sin(radiusChanger));
}
You can pass a function several arguments. Just separate them by commas:
1
2
3
function makeJuice(whichKind, howMuch, temperature){
// juice making instructions
}
More
Here is a nice, thorough discussion of functions: