Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many parameters are too many in JavaScript?

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:

  1. Why this discrepancy? Is it an off-by-one error in the language implementations?
  2. Does the ECMAScript standard impose this limit on function parameters?
like image 639
Aadit M Shah Avatar asked Mar 11 '16 18:03

Aadit M Shah


People also ask

How many parameters is too many for a function?

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.

What are the parameters rules in JavaScript?

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.

What happens if you have too many arguments in a function?

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.

Why do JavaScript functions not check the number of arguments received?

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:


1 Answers

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

like image 139
ObjectMatrix Avatar answered Oct 23 '22 08:10

ObjectMatrix