What are Parameters, Arguments and Arguments Object in JavaScript
In JavaScript, the terms parameters and arguments of a function are often used interchangeably. But there exists some difference between them. Let us see what they are with examples.
We are discussing the following things in this article
- What are parameters
- What are arguments
- What is an argument object?
What are parameters
Function parameters are the variables listed in the function definition. Let's take an example below:
function getSum(a, b){
return a+b;
}
Here, “a” and “b” are parameters in the “getSum()” function. Multiple parameters can be added inside parentheses, separated by commas.
What are Arguments
Arguments are values passed to the function when it is invoked.
function getSum(a, b){
return a+b;
}
var sum = getSum(1, 2);
In the above example ‘1’ and ‘2’ are the arguments passed to the “getSum” function.
What is an Arguments Object
The arguments object is an object which is a local variable available with all functions by default except arrow functions in JavaScript.
function getSum(a, b){
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
}
var sum = getSum(1, 2);
This object (arguments) is used to access the values passed to a function. It is only available within a function and can’t access from the outside. The arguments object allows you to access all of the arguments that are passed to that function as in the above example. It is not an array but, we can access elements using the index starting from 0, and it has a length property that contains the number of arguments passed to the function.
The arguments objects contain all of the arguments passed during the function call, even if there are not as many parameters in the function declaration. Look at the below example:
function calculate() {
console.log(arguments[3]);
// print 5 in the console
console.log(arguments[4]);
// print undefined in the console
}
calculate(1,2,3,5);
The output of the console.log(arguments[4]); is undefined because we are passing only four arguments to function calculate( ) which would be located at the 0 to 3rd index. But here we are accessing arguments[4] which is not available. So it is giving output as undefined.
On datainfinities.com, Read articles all around JavaScript, React, Node.js, PHP, Laravel, and Shopify.
Related Blogs
How to Fix error:0308010C:digital envelope routines::unsupported
How to fix npm ERR! Missing script: "start"
Find greatest common divisor (GCD) in JavaScript
Remove an item from an array in JavaScript
Cannot read property of undefined in JavaScript
node: --openssl-legacy-provider is not allowed in NODE_OPTIONS
ERESOLVE unable to resolve dependency tree error when installing npm packages
Invalid hook call. Hooks can only be called inside the body of a function component
The style prop expects a mapping from style properties to values, not a string
Explore All Blogs