|

JavaScript Functions Tutorial

javascript functions tutorial

JavaScript Functions are arguably the most important part of the language. As you begin to study them more deeply, you realize there is a lot more to them than meets the eye. This JavaScript series is really about covering the JavaScript Fundamentals, in order to build a solid understanding of JavaScript before we move into awesome JavaScript frameworks like jQuery and Node.js. If you are a student of Douglas Crockford, you’ll know it is in his opinion that JavaScript will be the language to rule them all, from Browser to Server, and back again. While that remains to be seen, JavaScript is here, it is widely used, and it provides many benefits, so we will need to get our hands dirty with it!


What is a JavaScript Function?

As we write more and more statements in our code, we need to take steps to keep things organized. To avoid things getting messy and disorganized, we can break apart large pieces of JavaScript into smaller, reusable blocks of code. As you know, all programming languages have this ability and JavaScript is no different.

Named Functions

The first way to create a function is to use the named approach.

  • Start with the keyword function.
  • Provide a name that is one word, with letters, numbers, $ and _, but can not start with a number and can not have spaces. The name should be descriptive of what the function actually does.
  • Next comes the Open and Closing Parentheses. If you expect to pass data into this function, the parameters will go in between the parentheses, separated by a comma.
  • Opening and Closing Curly Braces go next. In between these, you can place all of the JavaScript code that you want to run.
    This code can then be called by simply writing the name of the function followed by ().

In this example, we simply declare a function called learn, set a variable with the string Web Development Best Practices, then simply log that variable to the console. Go ahead, try it in Firebug now!

Where Should You Declare Functions?

When we give a block of code a name like we did in the example above, this does not actually cause the code to run when the JavaScript engine sees it. It is not until you actually call the function by name, that it actually executes. Now, we could have just as easily set up our function declaration and call in a different order like so:

This however is not a best practice. JavaScript likes to try and make things easy for you in different ways. One of them is by scanning your JavaScript first, before actually calling any functions. So yes, you could call a function before it is officially declared but this will only add to confusion when you or members of your team need to read the code at a later time. So be the good chap that you are, and define your functions first, then call them later 🙂

  • Declare all variables at the top of the function.
  • Declare all functions before you call them.

Functions With Parameters

Many times we need to be able to actually pass data to our functions to make them more usable. This is not all that different from any programming language you may be using. Let’s set up a function that doubles a number.

In this example we simple name a function called doubleIt which takes just one parameter, multiplies that number by 2, and logs the result. When we call the function passing in various number values, they do get correctly doubled.

Returning a Value

Most times, functions return a value. Almost all functions built into the language return some type of value, and when we write our own functions, we are probably going to want to return a value as well. We can return at any point in the function based on some logic, or we may simply want to do some calculations, and when we are finished return that result. Our example rewritten using a return statement would look like this:

Returning values is likely going to be a more useful approach.

Parameter Counts and Mismatches

Depending on what a function does, it may take one, or possibly many parameters. In other languages, the number of parameters given to the function when it is called must exactly match the number of parameters defined in the function declaration (minus any default parameters set in the declaration). You may have run across this where you accidentally pass too few or too many parameters to a function and the whole program comes to a screeching halt. No such behavior exists in JavaScript. Is this good or bad? Well, like many things in JavaScript, it just means that you really have to pay attention to what you are doing. In JavaScript you will often run across Silent Errors, or bugs which would have been found earlier if JavaScript wasn’t so forgiving. For example:

In this example, we have a nifty little function that accepts 4 parameters and calculates a mortgage for us. When it is called on the three following lines, we show an example of correct number of parameters, too many parameters, and too few parameters. Each instance has different behavior.

In JavaScript:

  • Extra parameters are simply ignored
  • Parameters not provided are set to undefined

Again, this is useful inasmuch as your code will not fail to run – but you need to pay attention, as most times you will want to actually pass the correct number of parameters to any given function.

Function Scope

In JavaScript there is no block scope, but there is function scope. What this means is that variables defined inside of a function, are only available for use inside that function.

local variable

global variable

The alternative to a local variable in a function is a global variable. Just be careful, it is thought that Douglas Crockford rains fire upon kittens each time a global variable is used in JavaScript. You still need to know how to use one however, and this is how you do it:

By declaring the variable result outside of the function, it is visible throughout the entire program. That is to say, it is a global variable.

Anonymous Functions in JavaScript

In JavaScript, function names are actually optional. We can also have functions that are nameless and these are called anonymous functions. They are everywhere in JavaScript applications, and getting a handle on them helps us to really make use of some of the power in the language, let alone being able to debug existing applications that make heavy use of them.

Here, we assign an anonymous function to the variable hi. We can then use hi like a function! Where we will see anonymous functions in a more real world situation is in the modern JavaScript frameworks. Here we will often see functions get passed as arguments to other functions, and this is where the real fun begins 🙂

Here is a super simple example to show passing a function as an argument to the JavaScript built in setTimeout() function.

When we run this script, it does exactly what it says it will do. It will wait for 2 seconds, and then log a message to the console. Use your imagination, think of all the incredible things you can do with this type of construct. It comes in very handy quite often.

Now the syntax is a little tricky if this is the first time you have seen it. Let’s look at it another way.

setTimeout(function() {var mes = ‘I will log to the console after 2 seconds’; console.log(mes); }, 2000);

This is simply setTimeout( arg1, arg2 ); with arg1 in italics and arg2 bolded. Hopefully that drives the idea home.

Anonymous Functions as Event Handlers

We recently covered JavaScript Events and how we can respond to those events. Well you guessed it, the anonymous function is the main way we can respond to events happening in JavaScript! Here’s a fun one. Let’s respond to the mouse movements of the user and take some action on every mouse move just for fun:

This is really easy. document.onmousemove is simply an event. function(){console.log(‘running’);}; is simply a nameless function (an anonymous function!) that we just assign to that event using the quite simple assignment operator =. The expression is as simple as something like var a = 'b';. As easy as you can declare a variable named a and assign a character b to it, so too can you specify an event and assign a function to it. Let’s test this out. I’ll run this code in firebug first, then just draw a few circles on the page with the mouse. Let’s see what happens.
javascript anonymous function

Ha! You can see, after making a few circles on the screen for a few seconds, our little event handler logged one thousand, two hundred and eighty one messages to the console!! Sure, it’s a funny example, but it shows the idea of how anonymous functions can respond to events in JavaScript.

Closures In JavaScript

Last up, we have a quick mention of Closures in JavaScript. Moving forward, we’ll dedicate a whole tutorial to just Closures in JavaScript, since it is an important concept in the language. For this example though, we just want to get the general idea of what a closure means.

We can have functions inside of other functions. Recall we said that in JavaScript, we have function scope. This means a variable inside a function is only visible in that function. So what happens when you have a function inside of a function? This is where closure comes into play.

  • An inner function has access to the outer function variables.
  • The inner function has access to those variables even if the outside function has already returned or finished executing.
  • One function closes over the variables of another function.

In the above example notice that we have a function named one, then inside of that function there is another function named two. Notice that function one accepts two parameters, and function two accepts no parameters. Also notice that function two is a self executing anonymous function. After this is all declared, we call the function one and pass in the numbers 5 and 10. Technically, function one doesn’t even do anything with these variables. When function one runs, inside of the body of that function, function two is going to execute. function two then writes out the variables passed in to function one to the console. What?! Function two doesn’t even take any parameters, how the heck is it able to write out the correct values? It is able to do this through closure, the inner function has access to the context of the outer function.

In this second example, we do something a little more complex. The example is inspired by the teachings of Douglas Crockford, and it is a bit of a mind bender, but once you get it, it helps cement the concept of closure in your brain. So what is happening in this code? Let’s observe just the outer function for the moment.

  • We declare a variable day.
  • We assign a self executing anonymous function to day. The () at the end of the curly braces for the function tells us that it executes immediately.
  • This function has two expressions.
    1. It declares a days array and populates it with a string representation of the days of the week.
    2. It returns a function. The second portion of this is tricky. You see, a function can be returned just like any other value. We are used to returning the result of a computation, or returning an array, or an object, but alas, we can also simply return a function from a function in JavaScript.

Now, let’s move on to this line theday = day(4);. There is a function in day. You would think it is the outer function assigned to day, since as we see in the first line var day = (function () {, there is an assignment operator = with a variable on the left, and a function on the right. Well, it must be that function in there, right? Wrong 🙂 Since the outer function executes immediately, it simply sets up the days array, and returns the function defined within it. This outer function is now done and complete. At this point, the inner anonymous function which takes a number as a parameter is what is stored in day! Now, that inner function runs, and we pass in a number, in this case 4 as an index. Remember, the outer function has already returned, so it’s variables should also be gone and no longer in existence – at least this is what you would expect. In reality however, this outer variable days, is still available to that inner function at this later point in time due to closure.