Have you noticed yourself writing the same group of code over and over again? Functions are a way to get rid of repeated code. Think of them as a combination of variables and comments. They are almost a way to organize your code with shorthand.

Functions have a simple format for something so helpful. Since they a variable, they start with the word var. Then you name the function like you would a variable as well. Next is = function(){};. The = function lets the computer know it’s not a variable. Inside the parenthesis are the parameters. The code you want to repeat goes in the curly brackets.

Don’t forget the semicolon!

Your code won’t work without it and it’s easy to miss when trying to find your error later on. So the format is: var name = function (parameters){code};. I normally format my repeat code like I would normal code.

The only new concept when using functions is parameters. This is the information you are going to put in when you “call” a function. When you create a function, think of it as making a machine. It’s great to have it but you have to put stuff in to get anything out of it. To call a function, type the name and then the parameters in parenthesis followed by a semicolon. The parameters can be x and y coordinates, size, variables, or colors.

If you want to use parameters in your repeated code, you need to enter it into your code. Let’s say you want to use your code to repeatedly make rectangles and you want your parameters to be the x and y coordinates. When you type your code for a rectangle put in a variable name for those coordinates. I use basic names like x and y, width and height, or color to avoid any confusion. Unlike normal variables, you don’t have to set a value for them outside your “call” code, unless you are using an actual variable as your parameter.

Functions are a great way to clean up your code. They allow you to label each set of repeat code like a comment while being able to quickly edit your code like variables. Next week, we will put into practice everything we have learned so far!

Leave a Reply

Your email address will not be published. Required fields are marked *