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
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.
The lesson brief states that “Functions can have zero, one or more parameters”.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With