p5.js Functions: Part 1

Objectives and Overview

In this lesson, you’ll learn about functions. Functions are one of the core concepts of programming, and understanding how to use them will save lots of time and expand your capacity for building out programs. Functions can be considered as subroutines or sub-programs that run within your larger code.

Lesson Objectives:

  • Understand and explain the aspects of functions and describe common uses.

Introduction to Functions

Functions are essentially groupings of code that are wrapped together and given a name that can then be called by the program at another point.

If you’ve worked with functions in math class, you may remember that they can take inputs, then perform operations on that input, and then output another value. Functions in programming work similarly.

Functions in JavaScript require a unique name. Additionally, you can specify the inputs that you want for your function by passing in arguments. Inside the function, you’ll write several code statements that will be executed when the function is invoked/called in your program.

There are several ways to create functions in JavaScript. This lesson introduces two of the most common ways. There are advanced construction processes that you may learn at a later point, but for right now just focus on understanding the basic purpose of functions in JavaScript.

Function Declarations

The first way to create a function is called a function declaration and breaks down like this:

function myFirstFunction() { console.log("Hello there! I'm a function!"); }
Code language: JavaScript (javascript)

In the above example, the function name is myFirstFunction() and there are no parameters that are passed as arguments. Even when there are no arguments for the function, you still need to include the (). If you omit these, it won’t register as being a function.
Additionally, every function needs to have curly braces at the start and end of the code statements. In the above example, the { is placed immediately after the () and then the } appears at the end of the function code, which in this case is just a quick console.log. Note that the code statements within the function require the use of a semi-colon but there isn’t one at the end of the function.

Functions must be called somewhere in your code. Think of the function as storing your code for later use. When you want to run the function, you would type the function name followed by parentheses, like this: myFirstFunction();

Function Examples in p5.js

The above example is a generic example of how to structure a function. You’ve actually already been using functions throughout your p5 programming. P5 is made up of the setup() and draw() functions, but now let’s look at another example. The p5 library has several functions that handle user events such as mouse and key presses. Events are important to understand when you’re designing anything with user interaction.

First, let’s examine two of these useful functions and then let’s build our own function!

The mouseIsPressed() Function

P5 has a useful function named mousePressed(). This is how p5 looks for whether the user presses the left mouse button. The code that you write inside this function is called (run) whenever the user presses the mouse. Let’s look at a code example:

let col = 0; // initial value of the color function setup() { createCanvas(600,600); } function draw() { background(50); // single value for background is gray scale. fill(col); ellipse(mouseX, mouseY, 50,50); } function mousePressed() { col = color(random(0,255), random(0,255), random(0,255)); // each mousepress randomizes the color }
Code language: JavaScript (javascript)

In the above example, the code inside the mousePressed() function is called whenever the user presses the mouse. Basically, whenever the mouse press event happens, the code within the mousePressed() function is called.

keyTyped() and keyPressed() Functions

The keyTyped() and keyPressed() functions work similarly to mousePressed(). The code that you write inside these functions is called whenever the user presses keys. By adding a series of conditional statements into the functions you’re able to write code that runs when specific keys are pressed. The keyTyped() is used for letter characters such as a, s, d, f, and keyPressed() can be used for special characters such as left and right arrows.

Let’s look at a modified version of the previous example:

let col = 0; // initial value of col let bgcol = 50; //initial value of bgcol function setup() { createCanvas(600,600); } function draw() { background(bgcol); //arrow keypresses will change background color fill(col); ellipse(mouseX, mouseY, 50,50); } function keyTyped() { //keyTyped watches for user pressing letter keys if (key == 'p') { col = color(255,0,100); //if user types 'p' change color to pink } else if (key == 'g') { col = color(0, 255, 200); //if user types 'g' change color to green } } function keyPressed() { //keyPressed can be used for special characters if (keyCode == LEFT_ARROW) { bgcol = color(255); //left arrow changes background to white } else if (keyCode == RIGHT_ARROW) { bgcol = color(50); //right arrow changes background to gray } }
Code language: JavaScript (javascript)

Play around with creating various effects by modifying the code inside these functions! Once you get a hang of how functions work, move on to creating your own.

Important: Functions and Variable Scope

When working with variables inside functions, there is an important property called scope that needs to be considered. Scope is either global or local.

Global variables are variables that are created outside of any functions, whereas local variables are variables created inside a function. Global variables can be seen and used by every function in your code, whereas local variables are only seen by the function that they’re declared in. Since p5 has several functions, such as the setup() and draw() functions, you’ll often want to create your variables outside of the function brackets.

If you need to be able to access the same variable in multiple functions, you’ll generally want to create a global variable. If you look at the examples used in this lesson, all of the variables are initialized outside of any function. This won’t always be the case when you work with other JavaScript applications, but for right now you can create your functions globally.

Activity: Function Practice

Add some basic interactivity to a sketch using the mousePressed()keyTyped(), and keyPressed() functions. These event functions will be important when you start adding mechanics to your game, so make sure that you understand how they work!

Activity Requirements:

  • Create a global variable in your sketch
  • Add code to the mousePressed() function
  • Use the keyPressed() function to detect at least two key presses
  • Add code to the keyTyped() function to detect at least two key presses

If you’re unsure of the differences between keyTyped() and keyPressed() refer to the examples!