Checking Object Type and Validating the Argument Type in JavaScript
July 30th, 2010 by Tweet
The “typeof” operator is very useful at the moment for checking what kind or type of object we are dealing with. It returns a string containing the datatype of the object. The values returned are “number”, “string”, “boolean”, “undefined”, “function”, and “object”. However, this operator has some flaws at the time of detecting an array or a null value which in those cases it returns “object”. Example:
var myObject = {},
myFunction = function(){},
myArray = [],
myboolean = true,
myNull = null,
myNumber = 1,
myUndefined = undefined;
typeof myObject; // "object"
typeof myFunction; // "function"
typeof myArray; // "object"
typeof myboolean // "boolean"
typeof myNull; // "object"
typeof myUndefined; // "undefined"
How to solve it?
With the help of instanceof We can create a function to determinate exactly what type of object it is. Example:
function typeOf(o){
var type = typeof o;
//If typeof return something different than object then returns it.
if (type !== 'object') {
return type;
//If it is an instance of the Array then return "array"
} else if (Object.prototype.toString.call(o) === '[object Array]') {
return 'array';
//If it is null then return "null"
} else if (o === null) {
return 'null';
//if it gets here then it is an "object"
} else {
return 'object';
}
}
Now we can easily execute the “typeOf” function to verify the real type of an object. Example:
typeOf([34,45,6,67,8]); // "array"
typeOf(null); // "null"
We are going to utilize this function as a helper to validate the type of the arguments or parameters of a function in the next section.
Argument Type Validation
As everybody knows, JavaScript is a loosely typed language, and we cannot declare arguments type in or method definitions. Some programmers have chosen different methodologies in order to avoid errors. One of them is the commenting the type of the parameter next it. Example:
function add(num1 /* number */, num2 /* number */);
This methodology works fine, the only problem is that it really does nothing. At the moment we pass a wrong parameter type, it would break our code and we can spend some time debugging just for a simple parameter. In order to solve this issue we can create a function “validArgs” that will use the “typeOf” function that we just created and performs some validation in the parameters passed to the function.
function validArgs(num, arrayType){
//get the parameters of the function that is executing validArgs
var args = validArgs.caller.arguments,
len = args.length;
//Check if the function get the number of parameter you are expecting. If not throw an error.
//If the parameter declared is 0 then do not perform this check
if(num){
if(num !== len){
throw new Error('The amount of paramerts allow it is ' + num + ', received '+ len);
}
}
//Verify the type of each of the parameters. If one is wrong throw an error.
if(arrayType){
for(var i = 0; i < len; i++){
if(typeOf(args[i]) !== arrayType[i]){
throw new Error('In parameter no. ' + (i+1) + ' the type should be ' + arrayType[i] + ', received ' + typeOf(args[i]));
}
}
}
}
The use of this function is very simple. In the first parameter we specify the amount of amount of arguments we are expecting in the function, and the second one is an array containing the the types of each parameter in the order the are expected. Example:
function add(n1, n2){
validArgs(2, ['number', 'number']);
return n1 + n2;
}
add(20,30) // 50
add(20, 'hello world') //Error: In parameter no. 2 the type should be number, received string
Conclusion
In conclusion, even though JavaScript is a loosely typed language, we can create some functions to solve this "problem". The beauty of JavaScript is that it is a loosely typed language and that gives you a lot of flexibilities at the time of coding an application. These functions can save a lot of time from debugging and I can recommend their use only in functions that you are expecting exactly one kind of arguments in their specific order. Hope you found this useful!
Wonderful resource for HP0-M38 dumps, ST0-099 braindumps, and testking 646-578 can be found here. Beside no need to worry for 1Y0-A15 and E20-591 if our dumps are there.
Teylor Feliz is a well-known XHTML/CSS/JavaScript enthusiast from Dominican Republic. He has more than 10 years experience in the computer programming, graphic design, and web development world, including 2 years teaching computer science. Teylor has a degree in Applied Sciences from the University of Louisiana and is completing a Master’s degree in IT with a concentration in Web Design and Development, at the University of Denver.
Subscribe to our RSS
Please help us to promote this article.






Thanks a lot for these interesting functions!
Great post. However, I found that the following could even be simplified:
function validArgs(num, arrayType){
//…
}
could be rewritten to:
function validArgs(arrayType){
num = arrayType.length;
// …
}
Also, I think in the production js code this function code should be taken out as it produces unnecessary overhead. Not much but still. It might be good for finding errors nevertheless.
validArgs function seems like a great idea, but there are some serious flaws within it that need to be addressed.
First of all, you didn’t declare the “args” and “len” variables with a var keyword, thus making them global variables, and we all know that global variables in javascript are pure evil
Second of all, you don’t need to use the “validArgs.caller.arguments;” statement to retrieve the arguments of a function. You can just use “arguments” and “arguments.length” without storing it in a variable, even though you’ll get a slight performance benefit when you’re storing arguments.length in a local variable. An example of this is a situation in which you’re using a loop statement with a local variable that stores the value of arguments.length, because referring to local variables is faster that referring to the property of an object; in this case, the length property of the object “arguments”
And third of all, why are you not handling your errors with try catch blocks?
Anyway, this is a great idea, and I will probably use it in my applications to force a little strictness in this loosely-typed language
. Tnx for that.
Cheers
@Koen
Thanks for your comment!
@Tim-Hinnerk Heuer
In that way I can be more flexible calling the function with one of the parameters. For example:
validArgs(2) //Validate only the amount of parameters or
validArgs(0,['object', 'number']) //No not validate the amount and only the check the types.
@Zlatan Halilovic
1) You are right, and I failed to declare those variables in this function. That happened at the time of pasting the code into worpress. You can see that the others variables have been declared in other parts of the code. And, it is true that the variables used without var goes to the global scope.
2) You cannot use arguments in this case because each function has arguments. If I call the arguments inside the function validArgs,then it is going to show an arraylike with the values of num, arrayType. However what I am getting with validArgs.caller.arguments is the arguments of the function from the “validArgs” is called. For example: When the “validArgs” function is called from inside of the “add” function, arguments in “validArgs” (has 2, ['number', 'number']), but validArgs.caller.arguments has (20,30).
3) I am not using try catch because I don’t want to catch that error and continue executing the code. I just want to display them immediately. This is just a single function to catch some errors in the development phase.
Thanks for your comments guys!!!
ahhh, so you just get the arguments of the caller, which is the add function in this case. I didn’t inspect the code a little closer so I misinterpreted that part, but thanks for the explanation
I will definitely use these code snippets in my dev, and it certainly does make sense not to handle the code with a try-catch block if the code is intended only for the development phase.
Thanks again for the comment!
This was really helpful! Thanks for all the great info and code.