GMT20230927-173708_RecordingEdit.mp4

Module 4 - Functions

https://docs.google.com/document/d/10xTO_QL339uKdS3Hme8EjLpvkSPprC_zzm-mukQI8lA/edit#heading=h.gjdgxs

Agenda of this Review Session

Functions

Programming with functions is one of the easiest ways to effectively break up your code into usable (and reusable) blocks in order to make your programs smaller, better organized and more understandable.

Functional Programming is an approach to software development which is used to describe the act of organizing your code into functions for the purpose of creating maintainable code.

You have already been coding with functions as almost all of the P5 functionality makes use of functions, for example rect(20,20,30) is a function that we have been calling to draw rectangles by passing the parameters that are needed to make a rectangle. We have also defined functions, for example setup() and draw() are examples of functions that we have created (or modified) in order to control our sketch. (Note setup and draw are both special functions in P5 as they get called automatically by the programming environment.

The following is an example of creating a very basic function that accepts no parameters:

function yourFunctionName() {
// a bunch of code to do stuff
}

function draw() {
  // To call your function just call its name
	//    with parenthesis
  yourFunctionName();
}

The following is an example of creating a very basic function that accepts 3 parameters:

function functionToDrawBlueSquare(ax,ay,aw) {
// a bunch of code to do stuff
	fill(0,0,200);
	rect(ax,ay,aw);
}

function draw() {
  // To call your function just call its name
	//    with parenthesis and pass 3 parameters
  functionToDrawBlueSquare(100,100,50);
	// Note we can call it a second time with different
	//    parameters
	functionToDrawBlueSquare(200,200,74);
}

The following is an example of creating a function with multiple parameters and a return variable.