JS: Function Parameters

By Xah Lee. Date: . Last updated: .

Number of Arguments Not Checked

JavaScript doesn't check the number of arguments passed in a function call.

function f (x) { return x;}

// extra arguments are ignored
console.log ( f(2,3,4) === 2 ); // true
// unfilled parameters have value of 「undefined」
function gg (x, y) { return y;}
console.log ( gg(3) === undefined ); // true

Parameter Default Value

Parameter can have default value, like this:

function f(param=value) {…}

For pre-ES2015, to define default values for optional parameter, you can just check if a argument is undefined, then set value.

[see JS: Function Argument Default Value]

Rest Parameters

A function can have unspecified number of parameters, like this:

function f (...name) { return name; }

That is, 3 dots followed by a name. In function body, the name is received as a array.

The syntax ...name must be the last item in parameter declaration.

[see JS: Function Rest Parameters]

Function Argument Destructure

[see JS: Function Argument Destructure]

the 「arguments」 Object

[see JS: Function's “arguments” Object]

How to find the number of arguments passed?

The number of arguments passed is arguments.length.

With ES2015 onward, you should avoid using this feature.

[see JS: Function's “arguments” Object]

How to find out how many parameters are declared?

Function has a .length property. Its value is the number of parameters declared in the function.

console.log (
    (function (x,y) {return x + y;}) .length
// 2

With ES2015 onward, you should avoid using this feature.

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon