Javascript Function.length

The length property returns the number of formal parameters listed inside a function.

Example

// function definition 
function func1(a, b) {
}

// finding the number of parameters inside func1 console.log(func1.length);
// Output: 2

length Syntax

The syntax of the length property is:

func.length

Here, func is a function.


length Parameters

The length property does not take any parameters.


length Return Value

The length property returns the number of formal parameters of the given function.


Example 1: Using length Property

// function definition
function func() {}

// finding number of parameters inside func() console.log(func.length);
// function definition function func1(a, b) {}
// finding the number of parameters inside func1() console.log(func1.length);

Output

0
2

In the above program, we have used length property to find the number of parameters inside func() and func1().

The func() doesn't have any parameter so func.length returns 0. There are two parameters a and b in func1 , so func1.length returns 2.


Example 2: length Property with Array of Arguments

The length property returns 0 when an array of arguments is listed inside the function. For example:

// defining a function with an array of arguments
function func2(...args) {
}

// finding number of parameters inside func2() console.log(func2.length);

Output

0

In the above example, an array of arguments is listed inside func2(). So func2.length returns 0.


Example 3: length Property with Default Parameter Values

The length property excludes the rest parameters and only counts parameters until the first one with a default value. For example:

// defining a function with default parameter
function func3(a, b = 10, c) {
}

// only parameters before the one with // default value are counted console.log(func3.length);

Output

1

In the above program, func3.length skips b which has a default value and c which comes after the default value. So, the method returns 1.


Did you find this article helpful?