How a Function Functions. Fun.

I’ve been helping out a lot of newbies of late, coaching them through code and helping them get a handle on some of the basics. I’ve discovered of late that there are a lot of people who follow the lines given, and while they kind of understand what it means, they are green enough right now that some of these basic concepts haven’t yet sunk in.

There is nothing wrong with this! We all start somewhere. For many of us as well, just following courses on-line without someone more experienced to show you the in and outs and help explain why can lead to a lack of knowledge of some of the … Well the whys  of how code does what it does!

So. This is very basic stuff in this blog post, but I figured I would put it out there so when people search … maybe they find it. Since I’ve had to talk at least a couple of people through this concept then well somewhere the information isn’t being communicated well enough!

First things first. Function

A Function, also often called a Method, is a distinct bit of code that sits outside the rest of your program. It never runs on its own, it only runs when it is called.

Of note, most modern languages call them Methods. Older languages before Object Oriented Program called them functions and as such those are often known as Function Languages. Then you have JavaScript, which can be very much OOP but to declare a new method you say function … so they are functions. Yay JavaScript. Because I am using JS in this post and when I first learned to code OOP didn’t yet exist, I will stick to function.

We’ll be using JavaScript not because it is my favorite (it’s not) but because that was the most common language the people I was explaining this bit of functionality (hyuck) used.

declare.png

The image above is how you declare a function. This is just what it sounds like. You are declaring the code that follows inside the { } block to be used whenever the name is used elsewhere. 


As an aside, there are different naming conventions for functions and how to name them. Often your IDE will help in this regard, but for the most part it’s best to use what is called “Lower Camel Case” - start with a lowercase letter, and each word in the name gets an Uppercase letter to make it easier to read. thisIsAFunction is lowerCamelCase.

Also, with old code and old IDE’s it was not easy to write things over and over so people often made abbreviations in their names or used one letter variables. This is no longer necessary! All modern IDE’s have smart systems to help complete your variable or function names.  Make that name descriptive. Tell us what it does. convertVariableIntoThisObject() or runStatisticalAnalysisOn(). It helps make the code easier to read when you don’t have to go find the method and puzzle out its code if it does what it says on the tin. If you want more on that, and other great concepts for writing code that is easy to read, check out the book Clean Code by Robert C Martin.


The main advantage of writing functions is that you can reuse that code without having to write it a second time. This is known as calling a function. Anytime you want to run that bit of code that is in the block of the function, we call it by using its name and the ().


calling.png

There. Now we know how to declare and call a function. We can call thisIsAFunction() as many times as we want in our code.

There is a second part to a function. The return statement. This part of the function is what ends it (nothing after return will ever be run in that same block) and return is what sends back some value to wherever the function is being called.  This is where a lot of people I have been chatting with have been getting confused, so let us dive into the way it works in a semi high level overview of functions.

Now, prepare for my horrible Paint explanations of what happens where and why!

function step 1.png

First. We have a function with no return at the top. When you run your main program (everything outside of function calls) and it gets to that call, it looks up the instructions, run through them. But since there is no return at the end, it just finishes whatever it's doing, and goes back to the next line in the code in the main program.

The next function has a return. so we call it, (2nd green arrow), it runs through the function (2nd blue), then it returns whatever it is told to return. This goes into the Left Hand of the line of code. We call it left hand because it's left of the = sign that would be there.

Well. In this case there is nothing there. so whatever it returns ... just disappears into the ether. This is OK. Sometimes you have a function return a true or false just to say if it ran properly, but you don't need to check for it (you should, but you don’t have to).


As you can see here, when we call it again with a var aThing = thisHasAReturn() the same thing happens.  (please ignore my a Thing typo!) Goes back to the same code, (green), runs it (blue), returns (red) but this time we have a variable there. The = sign tells us to store the return value back into whatever is on the left hand side of it and … boom. Variable stored.
















function step 2.png

function step 4.png

Now something a bit more. console.log is a function, did you know that? Somewhere in the depths of code that make up console and tell it what to do is a function called log. When it is passed a variable from inside the ( ) then it knows what to do to put that variable up on the console for all to read. It is a specialized function that has to be attached to its object. That is more advanced stuff than this post (and also it is the very foundation of Object Oriented Programming).

With that in mind however… Now we see what a return does in this case. On a line with many parentheses code starts from the leftmost and innermost parentheses.  (I am about 95% certain I am correct on this and my google fu is failing me as my 2yo wakes up. So… possibly I am wrong on the order here! Yet I am mostly certain.)

So for here it evaluates (fancy words for runs the code) the thisHasReturn function. When that is done it returns a value of some kind. We can very much consider the code to look like then, after thisHasReturn() has finished to be …

Which we all know will send that value to the console.


Final bit. Parameters.

Now. Last thing. Parameters. Consider the following function declaration.

parmetersDeclare.png

When we want to call it we might do something like this…

parametersCall.png

Now it is very important to understand what is going on here. Let us go back to my wonderful Paint skills…

Parameters are the stand in for whatever variable we pass to the function. Inside the function you will refer to those variables by the name listed in its declaration (something1, something2). 

Except in special cases (which is outside the scope of this post) those variables are copied into that function code. They are not actually there. You can’t access something and anotherThing inside funWithParameters().  The purplish blue lines are copying the value into new variables called something1 and something2.

They are copied on a one to one, so first variable gets copied into the first parameter, second into the next, and so on.

Just like you can’t access something and anotherThing inside the function, you likewise can’t see something1, something2, and yetAnotherThing outside of the function. They only ever exist inside it. The value they hold may get passed back out (with the return statement) but it yetAnotherThing does not ever exist outside. (again with exceptions, but again, beyond the scope). You can use the picture here to understand that dynamic - variables inside one box cannot be seen or even exist in the other - the function and the return statements are bridges to move data back and forth between the two - but just the data. The names do not exist, and if you want to save that data once it’s returned you need to do something with it.

This is the basic of Scope. A variable has a limited scope of where it can be interacted with, and it can get pretty complicated with a bunch of different things like Global and Static and Reference - don’t worry about those now. Just remember that if a variable is declared inside a set of brackets { } then it it only exists within those, and ones further inside (nested) those brackets. Anything outside those brackets, even another set, it does not exist.

function param step 7.png

This is all very basic, but very important to understand.

Undoubtedly many reading this will have skimmed over most of it and been like, yep. Knew that.  That is good. I would hope anyone who has a couple of months of coding to understand this.

I have been helping a lot of very new newbies to code however. Like less than two weeks. Or never having coded before. Or wants to and has some things but is missing the basics. So I’ve gone over this lesson a couple of times already, and I figured I would codify it down into a blog post. 

I hope this helps you understand a bit more what is going on. There is a deeper level to go. Memory pointers and how the compiler / executable store the data when it is being created/run respectfully. But those are way more than a beginner needs to know. That is one of the most wonderful things about code though. As you discover more, you learn there is more to discover, and yet you can still do things with what you know.

Previous
Previous

These are a Few Of My Favorite Things

Next
Next

A Slight Break