Introduction to Functions

Thus far we've been writing small scripts that do one particular task and then are "done." These are more exceptions than rules in the greater scope of programming, wherein we will have many moving parts and pieces, and it becomes important to be as clear as possible as to what each component is doing.


Motivation


Moreover, we may want to encode some behavior that we want to use again later; take a look at the following script:

  // Ask a user for 2 nums and alert true if the second is
  // a divisor of the first
  let num1 = parseInt(prompt("Give me a number...")),
      div1 = parseInt(prompt("And I'll tell you if this one is a divisor!"));
  
  alert(num1 % div1 === 0);
  
  // ...but then do it again!
  let num2 = parseInt(prompt("Give me a number...")),
      div2 = parseInt(prompt("And I'll tell you if this one is a divisor!"));
  
  alert(num2 % div2 === 0);

Warning: there are many stylistic problems with the above! Name a few of them.

  • Keep code DRY! (Don't Repeat Yourself). Repeated code that is meant to achieve the same behavior violates the principal of one-change, one-place. If you ever want to change behavior (e.g., in the above, allowing for floating point values), you should only need to change that behavior in one location in code.

  • Poor variable naming. Variables with numbers tacked onto the end that are meant to distinguish them from other variables of the same root name are generally poor practice; repeating code usually lends itself to poor naming in this manner, and leads to problems of clarity.


Function Overview

Just as we can think of variables as labeling values, so too can we rely on a new mechanism called a function that labels behavior.

We've seen functions in the familiar syntax of mathematics: y = f(x) = m*x + b is the traditional equation of a line in which y is expressed as a function of x.

In this sense, we say that a function named f is parameterized by some argument x, and then returns a value decided by the slope-intercept equation.

In future lectures, we'll look at how to define functions that look like this (programmatically) as well, but for now will turn our sights at a simpler formulation.

In this first lecture on functions, we'll look at a restricted function known as a procedure, which is a function that takes no arguments, but is meant to serve as a template for behavior.

The syntax for defining a procedure template is:

  function functionName () {
    // Function body: put the stuff you want
    // to execute here!
  }

Once you've defined a function and its behavior, the instructions in its function body can be executed by a function call with the syntax: functionName();

In good software engineering practices, we discuss using functions as tools for separation of concerns, wherein we can decompose a big problem into smaller, bite-sized chunks that are easier to structure and debug.

In other words, instead of writing an application as one quivering mass of statements, we can decompose it into smaller pieces written as functions, which elicit the desired behavior once called.

Try to create a function called divisorPrompt that abstracts the behavior we repeated above, and then simply call it twice to achieve the same behavior!


Note that we've been using functions all along and just not known it, though we haven't always used procedures (and there are several different function classifications).

The alert(str); function is provided by the browser to generate a popup with the text str, but we've only made calls to alert, not seen its definition.

Just how to make parameterized functions (and what the implications are) will be a topic of a future discussion.

Yet, the notion of using someone else's functions to help us practice with them is an appealing idea...



Introduction to Libraries

Recall: computer scientists are lazy... well, maybe that's too cliche to say... we like to work smart when possible, rather than hard (who wouldn't?).

Alongside the dubious work-ethic is a necessary notion of not always wanting to reinvent the wheel -- why spend time creating a hammer that you need when you'd rather spend time building the house?

For this reason, we can take advantage of many functions that others have written in order to serve our particular application of interest.

A JavaScript Library is code that can imported to make use of pre-written functions (and other tools we have yet to learn about).


Using Libraries


To make use of a library, we follow several steps:

Step 1: Import the library such that the script you are writing has access to it.

Just how you include libraries (in general) will be a topic of future discussion, but we'll make use of CodePen's convenient import mechanism in the example that follows.

To include an external script in CodePen, navigate to Settings > JavaScript > Add External Scripts / Pens.

Once we have a library in the project, we have access to its available functions... but how do we know what functions are available to us?

Step 2: consult a library's documentation / reference, which is generally a list of all available functionalities, and descriptions of how to use them.

Typically, libraries will come with some tutorial elements that help us understand how to use them at a basic level, and then expose the specific references that we can use to investigate further.

Once we know what functions we want to use, and have examined the documentation for how to use them, we're ready to... you know... actually use them!

Step 3: Use the library!

With knowledge from the documentation in hand, we can actually use the functions we've learned about to suit our specific application. When in doubt, Google will be our friend!


Whew! That's a lot of words and definitions... why don't we just jump into an example so we see all the parts in motion?



The p5.js Library

A picture is worth 1000 words (of code we didn't have to write because we'll use a library). - Anonymous

I made that a quote because it seemed appropriate, but it's not very anonymous at all, I just made it up on the spot.

Why don't we have some fun? Let's draw and animate some stuff!


Graphics in the Browser


There are a number of mediums through which to create graphics and animations in the browser; we'll look at one of them which is known as the Canvas element.

A Canvas element is like an artist's canvas on a webpage: an area defined by some number of width x height pixels on which one may "programmatically paint."

A canvas element's pixels are coordinate (X, Y) pairs, (0, 0) is at the top-left corner.

By "programmatically paint," I mean that you can use certain JavaScript functions to generate content on the canvas, and even animate that content!

Rather than start from first principals (your graphics class will cover that in detail), we'll use a library to help us get our feet wet!


The p5.js Library


The p5.js library is one (among others) library used to create graphics and animations on a Canvas.

First things first, let's look at what it can do (click on a few example animations in which you also get to see how they're implemented!):

p5.js Examples


These might look intimidating at first, but don't worry! We can take some baby steps and build our way up to the big-leagues.

A good place to start is the documentation -- what functions does p5 provide that we can use? Take a look:

p5.js Documentation

Wow, that's a lot to take in! Let's just try a simple example and then consult the reference as we go:


Using p5.js


Let's head over to CodePen and try out p5.js. To do so, we go to Settings > JavaScript > External Scripts, and look for p5 in the search window. It should pop up right away!

Now that it's imported into our project, let's try a simple example...

Create a scene of a sunny day with blue sky and green grass! (idea taken from Dr. Toal, but we'll make some changes of our own)

Using p5.js, the setup function is special and is called once at the start of the script.

So, if we want a static scene, we can pack all of the code we want into setup, and see what happens.

Let's start by commenting what we want to do, then consult the p5 documentation to see how to implement each aspect!

  function setup () {
    // Create the Canvas
    // Make a skyblue background
    // Draw a grassy rectangle on the bottom
    // Draw a sun in the middle of the sky
  }

Note: we will be doing a live demonstration of this in class and taking note of how to find and then explain the information we want!

Here is a result we might arrive at for our first efforts:

See the Pen Japmmg by Andrew Forney (@forns) on CodePen.

Using our new knowledge about functions, try to refactor the above by separating concerns into: drawScene, drawSun


That's pretty and all, but let's get some movement!

The p5.js draw() function is special in that it is called (by default) 60 times per second! This allows us to modify where objects in the scene exist by updating their position within the body of draw().

Try to make the sun move horizontally across the screen, then reset once it's reached the other side!

Here's a (pretty cheesy) attempt at that:

See the Pen Moving Sun by Andrew Forney (@forns) on CodePen.


Disclaimer: note that we've seen some very basic ways to use p5.js, but there are so many other tools available to you (just look at the documentation)! You are not meant to memorize these, that's what the documentation is for, and if you're confused about anything within: ASK QUESTIONS!

With that scary disclaimer in place, it's your turn -- have some fun and be creative!

Add (1) a single cloud that slowly floats across the screen (hint: several white circles that are put close together and move together will work), and (2) another animation of your choice (up to you what you want to do for 2... that rhymed)!



  PDF / Print