Creating my own function from scratch, I defined myFirstFunction to print my name when called. It’s clear that this is a very basic use of functions, but I have to start somewhere!
A slightly more complex use of functions was introduced in the form of a block of code with repeated sections. I succeeded in my task of replacing the repeated sections with a function, making the program much simpler to read.
Understanding more about the uses of functions, I moved onto learning about variables in functions. Functions can use any variables declared before the function is called, not just variables declared before the function is defined. Variables defined outside a function are global variables and are accessible anywhere in the program once they have been declared. Variables defined inside a function are local variables, only available for use inside the function. When a function is called, the code inside it is run. If a variable is set inside the function, that variable applies and the global variable does not affect the output of the function in this case.
Just as I was starting to get my head around variables, Codecademy introduced parameters. These can be thought of as the input to the function, acting as local variables to the function body. Parameters are placed in the parentheses after the word function and are important because they allow the use of one function to do an action with any piece of input. In the case put forward in exercise 5, parameters are used to say hello to any name entered. When calling the function, the name is added into the parentheses after the name of the function being called.