I came across the following question on StackOverflow: How many parameters are too many?
This got me thinking, is there a practical limit imposed on the number of parameters of a JS function?
test(65536); // okay
test(65537); // too many
function test(n) {
try {
new Function(args(n), "return 42");
alert(n + " parameters are okay.");
} catch (e) {
console.log(e);
alert(n + " parameters are too many.");
}
}
function args(n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = "x" + i;
return result.join(",");
}
Turns out, JavaScript imposes a practical limit of 65536 parameters on functions.
However, what's interesting is that the error message says that the limit is 65535 parameters:
SyntaxError: Too many parameters in function definition (only 65535 allowed)
So, I have two questions:
I've never seen a guideline, but in my experience a function that takes more than three or four parameters indicates one of two problems: The function is doing too much. It should be split into several smaller functions, each which have a smaller parameter set. There is another object hiding in there.
Parameter Rules. JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.
If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object. 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.
JavaScript functions do not check the number of arguments received. If a function is called with missing arguments (less than declared), the missing values are set to undefined. Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
Argument length limited to 65536 https://bugs.webkit.org/show_bug.cgi?id=80797
There are different argument count limits, depending on how you test: http://mathiasbynens.be/demo/javascript-argument-count
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