Home 07: Functions - parameter
Content
Cancel

07: Functions - parameter

Parameters work like variables that you create when calling your function. You can only use them inside your action block, so only between the curly braces of your function definition.

You define a parameter by writing its name inside the brackets of your function, like this:

1
2
3
4
5
6
7
8
function eye(x) {
  fill(255, 255, 255);
  stroke(0, 0, 0);
  ellipse(x, 30, 30);

  fill(0, 0, 0);
  ellipse(x, 30, 10);
}

To call the function with a parameter, you can either put in the value directly:

1
2
3
4
5
6
7
8
9
10
function eye(x) {
  fill(255, 255, 255);
  stroke(0, 0, 0);
  ellipse(x, 30, 30);

  fill(0, 0, 0);
  ellipse(x, 30, 10);
}

eye(50);

A single eye on canvas We can still see the single eye

Or you can use a variable and use that:

1
2
3
4
5
6
7
8
9
10
11
function eye(x) {
  fill(255, 255, 255);
  stroke(0, 0, 0);
  ellipse(x, 30, 30);

  fill(0, 0, 0);
  ellipse(x, 30, 10);
}

let leftEyeX = 50;
eye(leftEyeX);

Multiple parameters

If you need more than one parameter, you can write it after the first one, divided by a comma (,), like this:

1
2
3
4
5
6
7
8
9
10
function eye(x, y) {
  fill(255, 255, 255);
  stroke(0, 0, 0);
  ellipse(x, y, 30);

  fill(0, 0, 0);
  ellipse(x, y, 10);
}

eye(50, 30);

A single eye on canvas The same result with x and y as parameters

The position of the parameters is important. The first parameter name will correspond to the first value when you call the function, the second parameter name to the second value, and so on. In this example, the first parameter is named x and the second is named y.

You can use the parameters like variables inside the action block of your function.

1
2
3
4
5
6
7
8
9
10
function eye(x, y) {
  fill(255, 255, 255);
  stroke(0, 0, 0);
  ellipse(x, y, 30);

  fill(0, 0, 0);
  ellipse(x, y, 10);
}
eye(50, 30);
eye(100, 30);

Two eyes on canvas You can see both eyes now in different positions

Please note, that you can choose the parameter yourself, just like it is with variables. And if your parameter is not a position, but a color for example, you should choose another name.

About scope and variables

As you remember from the beginning of this chapter, variables inside of an action block and outside of it, are different.

For example, you can have the variable x and y defined on a global level, that means outside of your action block, and inside of the action block. They can have different values and they are not the same.

This post is licensed under CC BY 4.0 by the author.
Contents