Languages
[Edit]
EN

JavaScript - how to check number of arguments of function?

14 points
Created by:
AnnLen
9180

Using JavaScript it is possible to check number of arguments of any function in following ways:

  • currently called function provides invisible arguments variable available only inside function body - we can use it to check passed¬†arguments,
  • using spread syntax (... syntax) we are able to present arguments as array - useful with arrow functions,
  • using length property with function reference¬†we are able to check number of arguments - it doesn't mean the amount of argumkents should be same during calling.

Check below code to see details.

1. Function call arguments

Each function in JavaScript can be called with different number of arguments than are in definition.

1.1. Classic function example

// ONLINE-RUNNER:browser;

function doSomething(id, action, message) {
    console.log('Number of arguments for called function is ' + arguments.length);
}

doSomething(10, 'remove', 'Files from recycle bin removing.', 
    'File name 1', 'File name 2', 'File name...');

1.2. Arrow function example

Spread syntax was used to present arguments as array.

// ONLINE-RUNNER:browser;

let doSomething = (...args) => {
    // arguments keyword is not permitted in arrow function

    console.log('Number of arguments for called function is ' + args.length);
}

doSomething(10, 'remove', 'Files from recycle bin removing.', 
    'File name 1', 'File name 2', 'File name...');

2. Function definition arguments

This approach can be used for classic and arrow function definitions.

// ONLINE-RUNNER:browser;

function doSomething(id, action, message) {
    // function logic...
}

console.log('Number of arguments for function definition is ' + doSomething.length);

 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join