If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Review: Functions

This is a review of what we covered in this tutorial on functions.
We often want to be able to re-execute blocks of code when we are writing programs, without having to re-write the block of code entirely. We need a way of grouping code together and giving it a name, so that we can call it by that name later, and that's what we call a function.
To create a function, we must first declare it and give it a name, the same way we'd create any variable, and then we follow it by a function definition:
var sayHello = function() {
We could put any code inside that function - one statement, multiple statements - depends on what we want to do. In this function, we could just output a message at a random location:
var sayHello = function() {
   text("Halllllllo!", random(200), random(200));
Now, if all we do is declare the function, nothing will happen. In order for the program to execute the code that's inside the function, we actually have to "call" the function, by writing its name followed by empty parentheses:
And then we could call it whenever we wanted, as many times as we wanted!
We often want to be able to customize functions, to tell the program "well, do all of this code, but change a few things about how you do it." That way we have code that is both reusable and flexible, the best of both worlds. We can achieve that by specifying "arguments" for a function, using those arguments to change how the function works, and passing them in when we call the function.
For example, what if we wanted to be able to say exactly where we want the message displayed, just like we can say exactly where we want to draw rect()s and ellipse()s? We could imagine calling it like so, to put the message at two precise coordinates:
sayHello(50, 100);
sayHello(150, 200);
To make that work, we need to change our sayHello function definition so it knows that it will receive 2 arguments, and then uses them inside:
var sayHello = function(xPos, yPos) {
   text("Halllllllo!", xPos, yPos);
The arguments that get passed in basically become like variables inside your function definition, and the names depend on what you call them in the parentheses. We could just as easily rename them to something shorter:
var sayHello = function(x, y) {
   text("Halllllllo!", x, y);
Our functions can accept any number of arguments - zero, one, two, or more. We could have also decided that we wanted to change our function to accept a name to say hello to:
var sayHello = function(name) {
   text("Halllllllo, " + name, random(200), random(200));
And then we would have called it like so:
We could combine those ideas, and have it accept three arguments, for the name and position:
var sayHello = function(name, x, y) {
   text("Halllllllo " + name, x, y);
And then call it like so:
sayHello("Winston", 10, 100);
It really depends on what you want your functions to do, and how much you want to customize what they can do. You can always start off with no arguments, and then add more as you realize you need them.
Now, you've actually been calling functions this whole time - that's how you've been making drawings and animations - like with rect, ellipse, triangle, etc. All of those functions are ones that come from the ProcessingJS library, and we load them into every program that you make here, so that you can always use them. We've defined the functions for you, because we thought they'd be useful, and now it's up to you to decide what custom functions you want to use in your own programs. For example, we provide the ellipse function, but we don't provide a cat function - if your program involves a lot of different cats in different locations, maybe you should create your own cat function!
There's another powerful thing we can do with functions - we can use them to take in some values, compute them, and return a new value. Think about all the things you can do with a calculator - add values, subtract, calculate square root, multiply, etc. All of those would be done with functions that took in the input and output the result. The functions would take in the input as arguments and output the result using a return statement. Here's a function that adds two numbers and returns the result:
var addNumbers = function(num1, num2) {
  var result = num1 + num2;
  return result;

var sum = addNumbers(5, 2);
text(sum, 200, 200); // Displays "7"
The return statement does two things: it gives a value back to whoever called it (which is why we could store it in the sum variable), and it immediately exits the function. That means it'd be silly if we had something like this, because that last line would never get executed:
var addNumbers = function(num1, num2) {
  var result = num1 + num2;
  return result;
  result = result * 2; // silly!
Functions with return values are quite useful for manipulating data in programs, and they can be combined together in expressions, too:
var biggerSum = addNumbers(2, 5) + addNumbers(3, 2);
You can even call functions inside function calls, although that can get hard to read at times:
var hugeSum = addNumbers(addNumbers(5, 2), addNumbers(3, 7));
Now that you know how to create functions that wrap around blocks of code, we have to bring up an important concept: local variables versus global variables.
When we declare a new variable inside a function, we say that it is local to that function. That's because only that function can see that variable - the rest of the program outside of it cannot. Once we're outside that function, it's like it no longer exists. In the following function, localResult is a local variable:
var addNumbers = function(num1, num2) {
  var localResult = num1 + num2;
  println("The local result is: " + localResult);
  return localResult;
addNumbers(5, 7);
println(localResult); // oh noes!
When we run that code, we'll get an error on the final line: "localResult is not defined." The variable is only defined inside the function, because that's where we declared it with the var localResult = line, and is not defined outside of it.
When we declare a variable outside our functions, we say that it is a global variable. That's because all functions can now access it and do whatever they want with it.
var globalResult;

var addNumbers = function(num1, num2) {
  globalResult = num1 + num2;
  println("The global result is: " + globalResult);
addNumbers(5, 7);
When we run the above code, we will not get an error, because we declared globalResult outside of the function, so we can access it wherever we want.
⚠️ You might be tempted to use global variables for everything, since you'll never get an error that they're undefined. But actually, global variables are a common source of hard-to-find errors. In larger programs or collaborative programs, it’s easy to lose track of where and how you (or others!) used those global variables. When possible, use local variables.
Every programming language is different, but for JavaScript, it's important to know that variables have "function scope" - a function can see the local variables that were declared inside of it and the global variables that were declared outside of it, but it cannot see the local variables inside other functions.

Want to join the conversation?

  • leafers tree style avatar for user adnan.zubair
    question about draw()
    function some time looks to me a mysterious guy
    who calls it?
    When(in terms of timing) it is called?
    If it is called after a duration of time, What happens if previous a lengthy process in it has not finished, by that time?
    (278 votes)
    Default Khan Academy avatar avatar for user
    • orange juice squid orange style avatar for user Troy Cook
      The draw() function is called by Processing JS which interprets your program. It calls draw() from 1 to more than 200 times per second, depending on your computer speed, frameRate setting and how quickly the program executes. If your program takes a long time to run (more than a few seconds), then you'll receive an error and message asking you to make it simpler. If your program completely locks up (with an improper for or while structure) then your browser window may stop, causing you to lose the last changes you made after you saved it.

      The trick is to write your program so that it does everything quickly. If you have a process that is very complicated, then it will be necessary to separate it into smaller routines that can be called in order. That isn't the easiest thing to do, since your program must have some type of state or scheduling system.

      Most programs here aren't complicated enough to require a loading stage, and are able to render each screen quickly enough so the animation is smooth. This one takes the Pixelator data and draws just a little bit during each frame. Normally, the program would wait then display the complete image at once.
      (483 votes)
  • aqualine ultimate style avatar for user amy
    I was wondering if JS can be used outside of Khan Academy, and if so, where? If I were to do JS outside of Khan Academy, would I have sufficient knowledge to actually code?
    (63 votes)
    Default Khan Academy avatar avatar for user
  • spunky sam blue style avatar for user Jota Sprout
    What's the difference between an Argument and a Parameter? Are arguments for Functions and Parameters for Variables?
    (34 votes)
    Default Khan Academy avatar avatar for user
    • hopper jumping style avatar for user sun2gz
      An argument is the information in the parenthesis of the function in general. A parameter is the part that information plays in executing the function, or simply the argument variables in a custom function. They are different perspectives of the same thing.
      (7 votes)
  • leafers seedling style avatar for user iramschaudhry
    what is the difference between var draw and var mouseMoved?
    (15 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Dan Krallis
    Is this a good generalization of when to make a variable local or global

    Local - it appears that a variable should be made local when the desired output of the function its in wants to be based off specific parameters each time the function is called

    Global - it appears that a variable should be made global and placed in a function, when every time that variable is used its value wants to be whatever was the value of the last function call and parameter
    (2 votes)
    Default Khan Academy avatar avatar for user
  • male robot donald style avatar for user M***** H
    when you write your own functions, how could you include an optional argument(such as 'radius' in the 'rect' command)?
    (10 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Roger Sellers
    How do you generate random colors within a function?
    (8 votes)
    Default Khan Academy avatar avatar for user
  • leafers seedling style avatar for user Krzysiek Kowalski
    Hi KA people. Could anyone help me to achieve a goal which is to make fishes swimming independently from each other? Unfortunately the current code limits them to share the same dx value. I have implemented mouseClicked event which puts new fish to the aquarium with mouse coordinates and there is going to be a lot of fishes later on. I know how to that simple step do, but don't know how to keep a direction of each fish separately. Onwards, fishes are being drawn into canvas with a for loop. I'd like to stick to this concept. Pointing me to what should i learn to able to accomplish this *"independent swimming"* is more than welcome.

    (7 votes)
    Default Khan Academy avatar avatar for user
    • spunky sam blue style avatar for user Dalendrion
      Hi. I'm going to assume that you've stores the location of each fish in arrays.
      That means that each fish now has an independent position (for x and for y).
      You can do the same thing for velocity (for dx and for dy).

      Please let me know if that hint gets you where you want to go. :)
      (8 votes)
  • male robot hal style avatar for user Abdulrahman Saggaf
    Can I change the name of existing function? like changing draw to "D"raw or Plot?
    (7 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      Functions have no names. To keep track of them, we assign them to variables. draw is not a function. It is a variable declared by Processing.js. The agreement is that if you assign a function to its variable, then Processing.js will invoke that function numerous times per second.

      In general, it is easy to "alias" functions that you invoke, again via assignment. E.g.
      var Rect = rect;
      Rect(100, 50, 200, 300, 20, 0, 50, 10);
      (8 votes)
  • piceratops ultimate style avatar for user Akhil Jayanty
    If I want to run functions consecutively, like switching the screen instantly without animation, how would I do it?
    (6 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      There is no such thing as switching screens without animation. The canvas that you see is only painted once draw (or any of its related "special" functions) returns to its caller in the Processing.js library. So in
          background(255, 0, 0); // screen one    
      background(0, 255, 0); // screen two
      background(0, 0, 255); // screen three
      all you will see is the final blue screen.
      (8 votes)