Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking for invalid javascript function parameters

If i need to check a parameter i do this.

if ((typeof param == 'undefined') || (param == null)){
    param = ''; //or param = false;
}

And if it's meant to be a number i might throw in a isNaN check too. I was just wondering if there were any other things i should check for or what you do if you need to check your parameters. I know javascript has a lot of quirks that could affect something like this. What is good practice to check for?

Thanks

like image 795
Timothy Ruhle Avatar asked Mar 09 '11 03:03

Timothy Ruhle


People also ask

How do I check if a parameter was passed in to a function in JavaScript?

To check if a parameter is provided to a function, use the strict inequality (! ==) operator to compare the parameter to undefined , e.g. if (param !== undefined) . If the comparison returns true , then the parameter was provided to the function.

Can a JavaScript function have no parameters?

The lesson brief states that “Functions can have zero, one or more parameters”.

Why is my parameter undefined JavaScript?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined . The say() function takes the message parameter.

What are the function parameter rules in JavaScript?

The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.


2 Answers

Any object evaluates to false in a boolean expression if it is false, undefined, null, NaN, 0, "0", "false", or "" (the empty string).

To check for all of these at once concisely, you can just do it like this:

if(!param)
like image 111
Peter Olson Avatar answered Sep 30 '22 06:09

Peter Olson


I would simply pull a cliché and say that "it depends on what you want to do"..

If you just want to make sure the value is defined and sent to the function, the code you used should be fine.

You can of course also check for elements within the arguments array, like

if (typeof arguments[0] != "string") {
    alert("Has to be string");
}

// or even

if (arguments.length < 1) {
   // there aren't any parameters
}

etc...

the arguments array is very helpful in many ways. You can also use it to overload functions - to provide different functionality or arguments depending on the number of arguments provided, etc..

But other than that, I don't know what you need.

like image 43
arnorhs Avatar answered Sep 30 '22 07:09

arnorhs