Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint - Do not mutate parameter <x> when using 'arguments'?

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";
like image 278
robyaw Avatar asked Feb 21 '12 10:02

robyaw


People also ask

Should you mutate parameters?

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.

How are arguments passed in JavaScript?

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.

What is the use of this in JavaScript?

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.


1 Answers

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.

like image 107
Netlight_Digital_Media Avatar answered Oct 23 '22 04:10

Netlight_Digital_Media