The Definitive Guide to Javascript Functions

Javascript functions are blocks of code that and can be “called” an unlimited amount of times throughout your website or web application, just by referencing their name,  saving time when the repetition of code is required.

The syntax for a function is very simple:

function nameOfFunction() {
// The code goes here
}

After impementing that function you can then proceed to call it as follows:

nameOfFunction();

Here’s a simple function:

function numbersFunction() {
var X = 2
var Y = 5
document.write(X+Y);
}

That’s the initial function, which simply adds 2 and 5 together after being passed through the variables X and Y (the answer is 7 for you non-mathematical geniuses). Alone, however nothing is actually outputted on the screen. For that to happen you need to call the function:

numbersFunction();

In this case the number 7 would be shown on the screen, and this function can be called whenever and wherever you want. If you want to write numbersFunction(); ten times over, then the number 7 will be called ten times.

I remember when I first started bashing away at Javascript, the exact purpose of a function seemed a tad irrelevant – if I was going to write out the code anyway, why wrap it up as a single entity?

When you start building web apps you’ll begin to see how crucial functions are for readable, elegant code, but don’t feel you need your mind to explore all the possibilities. Be mindful of the functionality of a function and when the time is right it’s usage will “click” with you and you’ll be able to appreciate their purpose.

How to Effectively use Javascript Functions

Creating a function and then calling it once may allow you to make your code look a tad more sleek (with the ability to then hide all the messy stuff deep in a sub-directory) but you don’t get the true benefit of functions until you begin to call them multiple times, but do so in a way to vary their purposes.

This is the part of Javascript functions that I fail to see explained adequately time and time again, so pay attention – this is the good the stuff.

Let’s create a function called newFunction() that does the following:

  1. Sets a variable with the name “numbers”
  2. Stores the addition of two, not-yet-defined numbers in this variable

Pretty simple stuff – not exactly rocket surgery – but it’s a good lead in to more technical applications. Here’s the code in question:

function newFunction(x,y){
var numbers =  x + y;
}

You’ll see something new with this code. Instead of simply writing:

newFunction()

…we’ve added x,y in between the brackets. Explaining what’s happening is sort of difficult, so let’s just run the code and see what happens.

Type out the following to execute the function:

newFunction(2,5);

Can you guess what this does? It executes the function as you’d expect, but also replaces the X with the 2 and the Y with the 5, making it so, in this instance, the variable ‘numbers’ is equal to 7. You could change the execution code to:

newFunction(8,16);

…and then the variable ‘numbers’ would become equal to 24. To display the answer on the screen once it’s called, add the following code:

document.write(numbers);

…beneath the setting of the variable in the original function. The final code becomes:

// Create the function
function newFunction(x,y){
var numbers =  x + y; // Set the "numbers" variable
document.write(numbers); // Write the value of "numbers" to the screen
}

newFunction(2,5); // Call the function and pass the numbers into it

A Real World Example

Working with dummy code like this, while it acts as a simple introductory lesson, provides little context for when it comes to actually coding some functionality into an application. Let’s take a look at a real world situation.

When working on Minimalist Gmail, an extension for Google Chrome and my first real experience with Javascript (beyond hacking together code found on snippet sites) I had a file that would embed a stylesheet on a page (in this case, when you visited Gmail). The problem was, I had 9 different stylesheets and I wanted them to all launched under difference circumstances – if a certain preference was equal to X then load this CSS file, and if not, then don’t load this CSS file and so on and so forth.

As a complete beginner I took the easy way out and just copied and pasted the code 9 times, creating a hugely ugly and annoying to modify file that made it difficult to make big changes to the software (and this was early in development, so that was a big deal). Add in the fact that I had two other files just like this one and you can see I needed a more effective way.

In the original file here is the code I repeated 9 times over:

function hideMinimalist() {
var link = document.createElement("link");
link.setAttribute("href",chrome.extension.getURL("../css/minimalist.css"));
link.setAttribute("rel","stylesheet");
link.setAttribute("type","text/css");
document.head.appendChild(link);
}

The key part of this code is the use of the “minimalist” text which was an identifier pertaining to a single stylesheet. The fact that I had multiple stylesheets meant my code had to be duplicated to meet the functionality requirements. After procrastinating like a champ I implemented functions effectively and made the code look like this:

function hideStyle(styleName) {
var link = document.createElement("link");
link.setAttribute("href",chrome.extension.getURL("../css/"+styleName+".css"));
link.setAttribute("rel","stylesheet");
link.setAttribute("type","text/css");
document.head.appendChild(link);
}

I made three very simple changes:

1. Renamed the function hideStyle, as to make it relevant throughout the code.

2. Added styleName between the brackets, making the entire function header reading:

function hideStyle(styleName) {

3. Replaced the reference to minimalist.css with:

"+styleName+"

So, what’s actually happening with this code? Basically, I made it so this function could be applied to all situations where I needed to load a specific CSS file. All I have to do is type the following:

hideStyle("minimalist");

…and that function is called, and all instances of styleName (referenced in the original function, which now only needs to be written once) are replaced with “minimalist” (without the quotations). The code itself, when called, is identical, but the Javascript file containing this code was slimmed down significantly.

If I were to call the function as follows:

hideStyle("footer");

…then the executed code would be identical to that of the original example, but with the reference to “footer.css” file as opposed to that of “minimalist.css”:

var link = document.createElement("link");
link.setAttribute("href",chrome.extension.getURL("../css/footer.css"));
link.setAttribute("rel","stylesheet");
link.setAttribute("type","text/css");
document.head.appendChild(link);

Plus, if I were to make a change to the sole hideStyle(styleName) function, those changes would be reflected automatically in all other instances. Pretty spiffy, eh?

Being a fairly lazy coder myself however I’d recommend not fretting too much about finding places to effectively use Javascript functions. Even on small projects my code changes so much that polishing it too early ends up being a waste of time anyways.

Write your code as you usually would – duplication and all – and then ask yourself as you make progress: would this be a good situation to create a single function to do all the hard work? At some point, when you’re on the fine line between mesiness and unmanageable-ness, you’ll know it’s time to take a tad more pride in your work.

Leave a Reply

CommentLuv Enabled