Unit 3 Functions
Learning Activity 3

Return a value


Overview

In this learning activity we create functions that return values: first a number, then a boolean (true or false). Finally, we use the function that returns true or false as the condition for an if statement.

Instructions

1. Create a function that returns a value

In the last learning activity we created a drawHappyFace function. Like ellipse, fill, or background, drawHappyFace simply does a task. Some functions do their task, like a calculation, and then return its result to the main program. We have used functions that return a value before, random is one of them:

var a = random(2, 6);

In the code above, the random function does its task (picking a number between 2 and 6), and then returns its result to the main program, which stores the number in var a.

Let's create a function that does a calculation and returns its result. Below, distanceToMiddle calculates the horizontal distance between a position and the center of the canvas. In the example, the input position is called x:

function distanceToMiddle(x){
    var d = abs(width/2 - x);
    return d;
}

Note: abs is a p5 function that calculates the absolute value of a number. abs(-2) returns 2; abs(2) also returns true. Above, we use it so that no matter what the position of x is, we always get a positive number.

In this example, we use distanceToMiddle to set the size of an ellipse:

function setup() {
  createCanvas(600, 200);
  noStroke();
}

function draw() {
    background(0);
    var diameter = distanceToMiddle(mouseX);
    ellipse(width/2, height/2, diameter, diameter);
}

function distanceToMiddle(x){
    var d = abs(width/2 - x);
    return d;
}

Functions can return different types of values: numbers, strings, booleans (true or false), or even more complex objects, which we will learn about in the next unit. As an example, let's create a function called "mouseIsOverEllipse". It will check whether the mouse is over an ellipse. If it is, it returns true. Otherwise, it returns false. As you can see below, to specify the value to pass back we use the keyword return.

var x, y; //center of the ellipse
function mouseIsOverEllipse(){
    var result;
    //calculate distance between mouse position and ellipse position
    var d = dist(mouseX, mouseY, x, y);
    if (d < radius) {
        result = true;
    } else {
        result = false;
    }
    return result;
}

In the following example, mouseIsOverEllipse is called from inside an if statement that defines the fill color. This works because mouseIsOverEllipse returns "true" or "false", the kind of value typically expected by if statements.

To recap, when the distance between the mouse and the center of the ellipse is less than its radius, mouseIsOverEllipse will return true. This true result goes into the if statement, which directs the interpreter to the line of code that sets the fill to black.