An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
The obscure `Functionlength` property!
Today I found out about another super cool Javascript feature that I'll never use in my life, and I'm here to share it with you! Introducing Function.prototype.length
.
// there are 2 expected argumentsfunction foo(bar, baz) { // ...}foo.length; // so 2 is outputted
It's as simple as that! The length
property exposes the amount of arguments expected by the function in question.
Specifications
Rest parameters are not included in the final count!
function foo(bar, ...baz) { // ...}foo.length; // 1 - rest parameters are not counted
Also, only parameters before a parameter with a default value are counted.
function foo(bar, baz = true, foobar) { // ...}foo.length; // 1 - only parameters before one with a default value
What's the difference between arguments.length
and Function#length
?
As I described above, Function#length
will show how many parameters are expected in a function. However, arguments.length
(when used inside the function) will show how many were actually passed, regardless of whether they were expected.
function foo(bar, baz) { return arguments.length;}foo.length; // 2 - expects `bar` and `baz`foo(1, 2, 3, 4, 5); // 5 - five arguments were actually passed
Use Cases
You tell me! I have no idea
I hope you learned a bit about the Function#length
property! If you have any questions, corrections, or addons, I would love to hear them. Peace
Original Link: https://dev.to/lioness100/the-obscure-functionlength-property-32il
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To