- Parameters are variables listed as a part of the function definition.
- Arguments are values passed to the function when it is invoked.
Why should we bother about this minute difference?
In the code snippet above the function
argCheck takes three parameters
according to its function definition. On line 7 we call the function with an
extra argument and the code executes without any errors.
Similarly on line 11 we invoke the function with an argument less as compared
to the number of parameters and it still does not throw any error. Hopefully
this has convinced you that there is more to
Basically, when excess arguments are provided, they don’t get assigned to any
parameters. There are ways to access these excess assignments which we will
get to in a bit. On the other hand if we have more parameters than the
arguments, the parameters that have no corresponding arguments are set to
undefined. Lets explore JS features relating to arguments and parameters one
The arguments parameter
No that is not a typo. The
arguments parameter is implicitly passed just like
this parameter. It is a local variable accessible within all functions
and contains an entry for each
argument passed to that function. The
arguments object is an array-like construct which can be used to access
arguments passed to the function even if a matching parameter isn’t explicitly
See the code snippet above for the use of
arguments.length indicates the exact number of arguments which does not
depend on the number of parameters in the function definition. Individual
arguments can be accessed using array-like indexing notation.
One interesting feature of the
arguments object is that it aliases function
parameters in non strict mode. What this means is that changing
In the code snippet above
...restArgs creates an array
restArgs that holds
all the arguments passed to the function in an array. The rest parameter has to
be the last parameter otherwise it throws a
Syntax error : parameter after rest parameter.
Two major differences between the
arguments object and rest parameters:
Rest Parameters is a real array and methods like
sortcan be applied. Even though the
argumentsobject has the
lengthmethod, it is not a real array and using array methods like
sortwould only bring us misery and sorrow.
Rest Parameters contain only the
argumentsthat have no corresponding parameter while arguments object contains all the arguments passed to the function. Code snippet #3 could also be written as follows.
Hopefully the article provided some information on arguments and parameters and why it is important to differentiate between the two.