Validating JavaScript Function Arguments

Functions

JavaScript LogoGracefully handling corner cases is the key to writing more robust, error-free JavaScript.

If you work with JavaScript for a living, you write functions. There is just no way around this. So, if you write functions, then arguments are a part of your life. Now, if you are the only one who uses the JavaScript code you write, then life is pretty grand. But if you are writing code that will be consumed by others, then gracefully handling corner cases and errors becomes important; very important.

So, every time I write a function, I assume that someone else will call it. Even if I know no one will, I assume that someday, someway, someone will. Even if it never happens, I feel its a good habit to get into: write code that fails gracefully.

There are a zillion paths down which this conversation can go, but let’s focus on function arguments. When your function absolutely depends on an argument, and that this argument be of a certain type, and that it not be empty, or otherwise useless, you might have a recipe for disaster, if your hungry little function does not get what it needs.

Example # 1A

Example # 1B

In Example # 1A, we use an IF () block to make sure that the “arg” argument was passed-in before we attempt to do anything with it.

Good enough, right?

Not so fast…

Even though we have taken care to make sure we got the “arg” argument, what if our implementation code is a bit lengthy? Well, in Example # 1B we see how silly it is for all that implementation code to be wrapped in an IF () block. This kind of pattern breeds code that is annoying to maintain.

Example # 2

Ahhhhh, now that’s better!

So, as you can see in Example # 2, we simply say: “hey, if arg does not exist, then return.” This was accomplished using the JavaScript logical NOT operator. So, this means that if the argument “arg” does not exist, the function ends right there and none of the implementation code that follows is ever executed.

But…..

What if we need to be 100% sure that the argument “arg” is what we need it to be? What if it’s not enough to simply know that “arg” exists? What if we need to know that “arg” is an array and it has at least one element?

So many questions, so many darned questions.

Example # 3

Ahhhhh… that’s even better! In Example # 3 we’ve once again used the JavaScript logical NOT operator to say the following: “hey, if the argument someArray was not passed, OR if it is NOT an array, OR if it does NOT have at least one element, return.” This way, we can check for all the details we need in one neat little line and avoid a series of messy nested IF () blocks. We do our test, we feel good if none of the expressions evaluated to false, and then we proceed with confidence.

Summary

In this article we discussed function argument validation. We learned how to avoid wrapping our code inside of a large IF() block and validate the presence of the argument we need in one line. We also discussed how to test for the type of our argument, and the fact that it contains the minimum amount of data.

Helpful Links for the JavaScript Logical NOT Operator

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators

http://msdn.microsoft.com/en-us/library/ie/zz722703(v=vs.94).aspx

JavaScript Callback Functions – The Absolute Basics

Functions

JavaScript LogoCallbacks are a critical tool for properly handling asynchronous events in JavaScript.

Timing is one of the most difficult techniques to master in JavaScript. At first, many look to the setTimeout() method to address the asynchronous nature of JavaScript. But that is most often not the best approach. The concept of a callback function is one of the things that makes JavaScript such a special language.

In order to understand callbacks, it is important to be aware that functions are first class citizens in JavaScript. This means (among other things) that a function can be passed as a value to another function. The upside to this is the fact that if you call function A, and pass it function B as an argument, then inside of function A, you can execute function B. That’s really what it all boils down to: You call a function, and pass it another function. And inside of the first function, when an event that you need to complete has completed, you then “call back” to the function that was passed in.

While you can pass a named function as an argument, quite often you will see an anonymous function passed. Before we demonstrate a callback function, let’s demonstrate why they are so helpful in JavaScript.

Example # 1

PHP FIle:

Client-side JavaScript:

In Example # 1, we have two chunks of code: A server-side page that sleeps for three seconds, and then returns a JavaScript file. That JavaScript file simply outputs a message to the console.

When the script loads, it outputs a message to the console (message # 1). We want that message to be output before the 2nd message. The problem is that the script loading process is asynchronous; it could take 200ms, it could take five minutes. I’ve forced the PHP page that returns the JavaScript to “sleep” for three seconds, to exaggerate the effect. But the bottom line is: we don’t know how long that script loading process will take, which means that we have to find a way to execute message # 2 only after the script has finished loading.

Here is a JSFiddle link for Example # 1: http://jsfiddle.net/CZeLv/

Example # 2

In Example # 2, we pass an anonymous function to the getScript() method. Inside of getScript(), we take advantage of the fact that any dynamically loaded script element has an “onload” event. We assign that event to the callback that was passed-in. This means that when the script has successfully loaded, we execute the callback. As a result, we have complete control over the timing of events, even though the entire process is asynchronous. What happens is that message # 1 executes first, and then message # 2. This is what we want.

Here is a JSFiddle link for Example # 2: http://jsfiddle.net/dfCM2/

What if the script that we are loading has properties and methods that we need to act upon once the script is available? In Example # 3, we demonstrate how using a callback allows us to call a method that does not exist before the script is loaded, but we are able to control the timing of when it is called, so that it works every time.

Example # 3

PHP File:

Client-side JavaScript:

In Example # 3, after the PHP file “sleeps” for three seconds, it adds a new method to the window object. That method returns a secret word. We need access to that secret word in our page, but we need to make sure that we don’t try to call the method getSecretWord() until it is available. So by passing a callback to the getScript() function, we yield control to getScript() and basically ask it to fire our callback for us. Inside of getScript(), the script’s onload event is assigned to the callback, which means we only attempt to execute getSecretWord() once we know for sure that it exists (because the script’s onload event fired).

So the important thing to keep in mind here is that if the script we are loading takes five minutes to return, or never returns, it does not matter. Our callback will only fire when that script successfully loads. While it is loading, the user still has complete access to the browser. That is really important.

Here is a JSFiddle link for Example # 3: http://jsfiddle.net/fAn4g/

Summary

In this article, we covered the very basics of JavaScript callback functions. We learned that functions are first-class citizens in JavaScript, and can be passed to and from functions. We looked at an example of why callbacks are so critical to the JavaScript language and how they are an excellent tool for working around the asynchronous nature of the language,

Helpful Links for JavaScript Callback Functions

http://recurial.com/programming/understanding-callback-functions-in-javascript/

http://www.impressivewebs.com/callback-functions-javascript/

http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm