...

/

08 - Functions

08 - Functions

JavaScript Functions

Creating Functions

Functions are primary building blocks of JavaScript. They allow us to write programs in a more efficient and scalable manner. Functions help us to manage complexity by containing and grouping operations under a single executable name. We already know how to call functions by using the p5.js predefined functions such as ellipse or background. We even created our own functions as p5.js forces us to put our code into two function declarations, setup and draw. If we wanted to create our own functions, we would be following the same convention that we have been using for the creation, or declaration, of these functions.

To create (or to declare) a new function, we would start off by using the function keyword and then give the function a name of our choosing that ideally describes the behaviour or purpose of the function.

	function functionName() {
		// function body
	}

Next, to the function name we would open brackets. If we want to build a function that works with user input, we can define parameters inside the brackets that would act as placeholder variable names for the future user input. We will see how this works in a bit.

Then we have curly braces. Inside curly braces can be referred to as the function body. In there, we would write the code that would construct the logic of the function. We can also make use of the parameters, the variable names we defined inside the brackets next to the function name, as part of the operations we want to perform inside the function body.

Let’s look at a simple example. Notice how p5.js has an ellipse function but not a circle function. This is not really an issue since we can easily create a circle by providing the ellipse function with same width and height values. For argument’s sake, though, let’s create a circle function that would work with three values: ...

Access this course and 1400+ top-rated courses and projects.