How p5 Works

p5 wants you to define a setup () function, which it will run once; and a draw () function, which it will run after the setup function has been executed, and which it will loop indefinitely thereafter.

When you define a function, you use this syntax:

function nameOfFunction () {
    // code goes here
}

The word function here tells the computer that you are about to define a function.

The word after it, nameOfFunction, is an arbitrary name that I gave it - this can be any word except for those words already used by p5 or javascript to do other things (like 'function', for example). In this case, I have concatenated three words together using camelCase.1

When defining functions, the parentheses, (), after the function name, are here so we can specify some arguments, if our function needs arguments. Arguments are values or objects that we pass into the function for the function to use in some way.

The setup and draw functions don't need arguments, so we won't worry about them for the time being. This is a concept that we will return to a bit later -- just know for the moment that if these functions had arguments, this is where they would go.

The curly brackets, {}, specify the scope of the function. Which is another way of saying that any code that goes between these brackets will be executed when that function is called.

Calling a function, is different from defining a function. When you call a function, it looks like this:

nameOfFunction ()

Defining a function is like writing a set of instructions - in order for the computer to actually do those instructions, you need to call the function. When a function is called, the computer will execute the code between the curly brackets in the function's definition.

Normally, if you define a function, but never call it, the code doesn't do anything - you have written out instructions, but never told the computer to actually carry out those instructions.

The exception is in p5. In p5 we simply define the setup and draw functions, and p5 will take those definitions, and call those functions for you, behind the scenes.

First the setup function, once; and then the draw function, infinitely.

Footnotes

  1. Using camel case is a stylistic convention for javascript, but you are free to use snake_case if you prefer. In my creative coding practice, I like to use snake case. It is a matter of style -- the most important thing being that you are consistent throughout your code.