If one looks at the description of many of the functions defined in p5.js documentation, it is clear that
functions can have optional parameters. However, the references
https://p5js.org/reference/#/p5/function
and
https://p5js.org/examples/structure-functions.html
don't discuss the issue.
A method is simple terms is just a function that has been declared in a class. Our comments about functions apply to methods.
The following function is designed to help clarify the issue and shows how you can write functions with a variable number of parameters.
function testing(a, b, c) { var s = "a: " + a + ", b: " + b + ", c: " + c; if (a == null) { s += ". There are no parameters"; } return s; }
In p5.js the value of a missing parameter is null but they are displayed as "undefined". It is important to observe that p5.js insists that every "," in a function call is followed by a value. Hence testing(2, 3, ) and testing(2, , 5) are not allowed. Hence, the testing function concludes there are no parameters by just testing if (a == null).
Sometimes a function responds differently quite differently if it given no arguments than it has some. For example, function related to a particular variable be set that value if it has an argument but returns its value if it doesn't.
For example, suppose a class called Person has fields (a fancy name for a data variable in a class) for first name and last name. Further, suppose it has this 2 parameter method name(firstName, lastName).
name(f, l){ if (f == null) { return this.firstName + " " + this.lastName; } this.firstName = f; if (l != null) { this.lastName = l; } return; } // name
It operates as follows. If 2 values are supplied, it sets both the first and last names. But if only 1 value is suppled, only the first name is set. However, if no values are supplied, it returns a string containing both names. Here is the coding sequence displayed in the canvas.
let child = new Person("John", "Doe"); // initializes child to "John", "Doe" child.name(); // returns "John Doe" child.name("Sally"); // only changes the first name child.name(); // returns "Sally Doe" child.name("Mary", "Smith"); // changes both names child.name(); // returns "Mary Smith"
(The astute reader might notice the coding would be simplified if the function returned the name string every time even if the values were supplied for one or two of parameters.)
p5.js source code: HowToFunctionsVariableNumParams.pjs
James Brink 2/10/2020