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";
Mutating input parameters inside a function is a very frequent bad practice, and dangerous because it's made without awareness of the consequence, especially in multithread application.
Arguments are Passed by Value 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.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
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.
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