Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

...

...

Syntax of functions

There are two parts of a function. First there is the the function declaration, where the name of the function along with its properties and behaviors are defined. Next there is the function call, where the function is then actually executed. Functions may be called multiple times.

Functions can also accept input values (called parameters) that are sent to the function when called. These input parameters can change the behaviour of the function.

Functions can also return a value. This means when we return to the line where the function was called, it has now carried a number with it. In p5js, functions that have no return value are declared with “function” return type.

Function Declaration

This is how the function is named, its return type and parameters defined with sudo code.

datatype functionName (parameter,.....)

...

<function contents>

<possible return value>

}


Function call 

This is how we execute a function:

functionName(parameter,.....) ;


Function Examples

This example shows how to write functions with return values.

Code Block
linenumbers
languagejstrue
function setup()
{
  const result = calculateSquare(4); // assign variable to call a function
  console.log(result);

  print(calculateSquare(10)); // call function directly
}
 
function calculateSquare(x) {
  return x * x;
}

...

Code Block
languagejs
function setup(){
 createCanvas(300,300);
 background(0);
 stroke(255);
 strokeWeight(10); 
}

function draw(){
 point(mouseX, mouseY);
}

function mousePressed(){
 print("x:" + mouseX + ", y:" + mouseY);
 clear();
 background(0);
}

Exercise

...

Write a sketch where a unique shape follows the mouse position. When you click the mouse, the shape should change in some way (form, colour, size).