Functions combine multiple lines of code to perform an actions. What happens is that functions take several lines of code and combine them into a single line.
Here is another to explain them.
Every programming language lets you create blocks of code that, when called, perform tasks. Imagine a dog that does the same trick only when asked. Except you do not need dog treats to make your code perform. In programming, these code blocks are called functions.
All programming functions have input and output. The function contains instructions used to create the output from its input. It’s like a cow that eats grass (the input) which its body turns into milk which a dairy farmer then milks (the output).
For example, programming functions might take as input any integer or number. The function might create output by multiplying the input times two. Therefore, the output of the function would be double its input.
Or imagine the short Hello message you sometimes see in online software applications at the top right corner of any page. The function would take as input your name (or user number) from the application and drop your name (or look up your name with your user number) into the phrase “Hello [your name]!” If your name is Jane, the output of this function would be “Hello Jane!”
It is possible to build entire software applications with only functions. Programming languages which primarily use functions are called functional programming languages. Haskell and a few other languages are primarily functional languages. You build software by building blocks of code that perform specific tasks.
What does that mean? Well, let’s think about one of the main functions we already use.
function draw()
{
}
draw
is a function that is called continously when a sketch runs.
function draw()
{
}
Let’s breakdown the draw
function.
The draw function is built-in to p5.js. All programming languages have built-in functions. However, programmers can define functions too.
See the Pen Intro to Functions - p5.js by Michael Cassens (@retrog4m3r) on CodePen.