Main content
Computer programming
Course: Computer programming > Unit 1
Lesson 10: FunctionsReview: 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:
sayHello();
And then we could call it whenever we wanted, as many times as we wanted!
sayHello();
sayHello();
sayHello();
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:
sayHello("Winston");
sayHello("Pamela");
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);
println(globalResult);
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?
- 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?(284 votes)- 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.
https://www.khanacademy.org/cs/mona-lisa-stepix/5738515882049536(486 votes)
- 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?(66 votes)
- There is a site called JSfiddle. It's a programming website where you can be creative and make your own programs using Javascript, HTML, and CSS.(105 votes)
- What's the difference between an Argument and a Parameter? Are arguments for Functions and Parameters for Variables?(36 votes)
- Good question! I made this presentation to help you.
https://www.khanacademy.org/computer-programming/javascript-functions-jargon-explained/6661364542734336(78 votes)
- what is the difference between var draw and var mouseMoved?(16 votes)
- As far as I can tell, draw(); is called every single frame while mouseMoved(); is called every frame your mouse is detected moving.(13 votes)
- 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(5 votes)- Dan, local functions will work ONLY in the function they were declared in. A global function will work EVERYWHERE no matter where you use it.(42 votes)
- How do you generate random colors within a function?(11 votes)
- Any way you can generate random colors in the main part of the program will work within a function.(10 votes)
- when you write your own functions, how could you include an optional argument(such as 'radius' in the 'rect' command)?(12 votes)
- To make b optional with a default value use
var myFunc = function(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}
See
https://stackoverflow.com/questions/12797118/how-can-i-declare-optional-function-parameters-in-javascript(7 votes)
- Can I change the name of existing function? like changing draw to "D"raw or Plot?(9 votes)
- 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);(10 votes)
- If I want to run functions consecutively, like switching the screen instantly without animation, how would I do it?(8 votes)
- 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
all you will see is the final blue screen.background(255, 0, 0); // screen one
background(0, 255, 0); // screen two
background(0, 0, 255); // screen three(11 votes)
- 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.
https://www.khanacademy.org/computer-programming/spin-off-of-project-fish-tank/5478064221487104(7 votes)- 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. :)(9 votes)