← All lessons/Functions· Lesson 18 of 32

Defining your own function

Bundle a few lines of code into a named function with function name() {}, then call it to run them.

About 6 min

A function is a named bundle of code

You've already *called* functions like rect() and fill(). Now you'll define your own. A function lets you give a name to a few lines of code so you can run them whenever you want, just by saying their name.

function sayHello() {
  println("Hello!");
}
The shape of a function definition.

That defines sayHello, but nothing happens yet — defining a function doesn't run it. To run the code inside, you call it by writing its name followed by parentheses: sayHello();.

Define a smiley-drawing function, then call it.

Define then call

A definition sets up the recipe. A call actually cooks it. You can call the same function as many times as you like.

Your turn

Define a function named drawSmiley that draws a face: an ellipse for the head and two more ellipses for the eyes. Then call drawSmiley() once to run it.

Hints