The anatomy of a function

One of the things that i see developers who have just started learning about code is that they struggle with how a function works. So, I decided to write about how the anatomy of a function.

To make things simpler, I'm going to write everything in JavaScript.

The first part of a function is the function definition.



Above is our function definition. We are saying this is what we want our function to do.

myFunction is the name that we gave the function. We will use this name to call the function when we want it to execute it's instructions.

Inside the parenthesis, we have our parameter. It can be whatever we want it to be and can be any data type, including another function.

The curly braces are the starting and ending points of our instructions. It's like saying This is where the instructions start, and this is where they end

In between our curly braces we put what we want our function to do. In the above example we are saying for whatever parameter we pass into the function, do this with it. In the above case, we are passing in a value, that we are going to return inside of a string. Since functions are reusable, we are using a sort of placeholder for whatever value we want to pass into our function, which is called a parameter.


So, the next part of using a function is calling it when you want to use it.


Here we are calling our function by using the function name. If the function takes a parameter, we provide one, but at this point it's called an argument. The parameter, is the placeholder, and the argument is the real value. In this case, the argument is a string "Jennifer".

So, what happens when we call our function? It returns:

 Hello, Jennifer

Pretty cool, huh? So, what if we want to change our argument, and say return a different person's name? Well, that's not a problem, because functions are reusable. All you have to do is give a different argument. Here's how that will look: 

myFunction("Ernie")
Hello, Ernie

myFunction("Bert")
Hello, Bert


That's how a function works. For the function instructions, you can do just about anything. You can do calculations, print something to the console with console.log, and much more.

Comments

Popular Posts