Categories:

Detecting the existence of a parameter

We can further enhance a function so it doesn't have to accept a fix number of parameters. In order to do this, we need to detect if an argument has been passed into the function, or in this case, a member of the object, by checking for its existence. There are several ways to do this. You can use the in operator, the typeof operator, or finally, the automatic typecasting of undefined to false. However, these methods were mentioned in that order for a reason: they go from most reliable to less reliable. This is because the in operator detects if a member actually exists in an object (it may exist but be undefined), the typeof operator detects whether the member is (or, more commonly, is not) of a certain type, and autocasting tells you only whether the member has a value that evaluates to true (anything other than NaN, 0, false, undefined, null, or an empty string, that is).

Well let's look at some examples of these techniques for testing whether an object has a member: If not, a local variable is assigned an empty string ("") instead:

Example 1: The in operator
//Detect whether there is a "myparameter" member in the "oArg" object: 
var myparameter = 'myparameter' in oArg? oArg.myparameter : "";
Example 2: The typeof operator
//Detect whether type of oArg.myparameter is not "undefined':
var myparameter = typeof oArg.myparameter != 'undefined'? oArg.myparameter : "";
Example 2.1: The typeof operator version 2
//Assuming parameter is a string, detect whether type of oArg.myparameter is "string":
var myparameter = typeof oArg.myparameter == 'string'? oArg.myparameter : ""; 
Example 3: Autocasting
//Assign the value of oArg.myparameter to variable "myparameter" if it casts to true:
var myparameter = oArg.myparameter || "";

Sadly, the in operator has the worst browser support among the three methods, so using the other two is actually preferred until version five browsers are gone from the market. Well, now go experiment!

This tutorial is written by David Andersson (Liorean). Liorean is a twenty years old medical student and hobbyist web designer mostly working with JavaScript and CSS, DOM and the newest html standards available.