Reputation: 2320
All,
I use JSLint to validate my JS files. In my most recent project, I am using the following format to set default values for a number of JavaScript functions (further detailed here):
function(a, b, option) {
option = arguments.length > 2 ? option : "some default value";
// ...
}
This however causes the latest build of JSLint to produce the following error:
"Do not mutate parameter 'option' when using 'arguments'."
I am aware that using the more common method for assigning defaults (i.e., option = option || {};
) supresses the error; however, this will produce incorrect behaviour if I intend to pass a falsey value to option
.
Is the only solution to this issue to introduce a new variable? e.g.:
var option2 = arguments.length > 2 ? option : "some default value";
Upvotes: 6
Views: 1171
Reputation: 52581
In most situations you'd be better off just doing:
function(a, b, option) {
option = option || "some default value";
// ...
}
or
function(a, b, option) {
if ( !option || typeof option !== 'string' ) {
option = "some default value";
}
// ...
}
Upvotes: 0
Reputation: 414
I guess JSLint warns you since you try to modify one of the input arguments by using a check with the arguments keyword. JSHint, however, does give me any warning when trying your code.
A solution to your problem would be to check if option
is defined or not, that way you go around the problem with sending in falsy values:
function(a, b, option) {
if(typeof option === "undefined") {
option = "some default value";
}
// ...
}
If you find that it is cumbersome to write this typeof
check everytime, create an isDef
function:
function isDef(param) {
return typeof param !== "undefined";
}
function(a, b, option) {
option = isDef(option) ? option : "some default value";
// ...
}
// Simon A.
Upvotes: 6