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

All,

I use JSLint to check my JS files. In my last project, I use the following format to set default values ​​for a number of JavaScript functions (more here ):

function(a, b, option) { option = arguments.length > 2 ? option : "some default value"; // ... } 

This causes the latest version of JSLint to cause the following error:

 "Do not mutate parameter 'option' when using 'arguments'." 

I know that using a more common method to assign default values ​​(i.e. option = option || {}; ) suppresses the error; however, this will lead to incorrect behavior if I intend to pass false to option .

The only solution to this problem is to introduce a new variable? eg:.

 var option2 = arguments.length > 2 ? option : "some default value"; 
+6
source share
2 answers

I think JSLint is warning you because you are trying to change one of the input arguments using a check with the arguments keyword. JSHint , however, gives me a warning when trying your code.

The solution to your problem will be to check if option exists or not, this way you get around the problem of sending false values:

 function(a, b, option) { if(typeof option === "undefined") { option = "some default value"; } // ... } 

If you find it cumbersome to write this typeof check every time, create the isDef function:

 function isDef(param) { return typeof param !== "undefined"; } function(a, b, option) { option = isDef(option) ? option : "some default value"; // ... } 

// Simon A.

+6
source

In most situations, you will be better off:

 function(a, b, option) { option = option || "some default value"; // ... } 

or

 function(a, b, option) { if ( !option || typeof option !== 'string' ) { option = "some default value"; } // ... } 
+1
source

Source: https://habr.com/ru/post/908957/


All Articles