Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting parameters in Javascript

What the docs at Mozilla says:

  console.log((function(...args) {}).length); 
  // 0, rest parameter is not counted

  console.log((function(a, b = 1, c) {}).length);
  // 1, only parameters before the first one with 
  // a default value is counted

So how will I ever be able to count parameters in such cases ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length

like image 648
Tilak Maddy Avatar asked Nov 29 '25 06:11

Tilak Maddy


1 Answers

There are two separate things going on here with parameters defined and arguments actually passed.

For a defined function, you can get access to the number of parameters that are defined in the definition of the function with fn.length:

function talk(greeting, delay) {
    // some code here
}

console.log(talk.length);     // shows 2 because there are two defined parameters in 
                              // the function definition

Separately, from within a function, you can see how many arguments are actually passed to a function for a given invocation of that function using arguments.length. Suppose you had a function that was written to accept an optional callback as the last argument:

function talk(greeting, delay, callback) {
    console.log(arguments.length);     // shows how many arguments were actually passed
}

talk("hello", 200);    // will cause the function to show 2 arguments are passed
talk("hello", 200, function() {    // will show 3 arguments are passed
     console.log("talk is done now");
});                                 
like image 64
jfriend00 Avatar answered Nov 30 '25 19:11

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!