You can use functions to combine parts of your program. For example, you can combine multiple drawing commands and create new commands that you can use in your program instead. Functions are used to make your program better to read, easier to understand, and easier to reuse. You don’t have to repeat your code again and again.
You create functions with the keyword function
followed by the name of your function. The same naming rules apply to function names as to variable names. Next, you write an opening and a closing bracket that can contain parameter names, but we will talk about parameters later in this chapter. Now comes the so-called action block. It is surrounded by curly braces, and this is where you write the code that your function should execute.
1
2
3
function nameOfYourFunction() {
// Your code
}
Naming your function
Variables and functions cannot have the same name. If you reuse a variable name as a function name, that variable will be overwritten with your function.
The action block and scope
Everything inside the curly braces is called the action block. All variables you create inside of the action block with the let
or the const
keyword are only available there. You cannot access them from the outside. You can access variables from the outside, but be careful with that. You should try to avoid that (and you will learn in this chapter how you can avoid that, using parameters).
If you create a variable with the same name inside the action block and outside of it, they will be handled like different variables and they will not overwrite each other.
The action block is like a small program on its own, living inside of your code.