In this tutorial, you’ll learn How to read arguments from JavaScript functions. This question was asked to me during a JavaScript interview. Off course you can read arguments from the parameters to the function. But there is a way to read all function arguments as a single object or array list.
Using Arguments Keyword
The keyword arguments gives you all the arguments passed into the JavaScript function.
function foo() {
console.log(arguments)
}
foo(2,3);
You can access both the passed in parameters using the arguments object. arguments[0] and arguments[1] will give the parameters passed to the JavaScript function foo.
Using Rest Operator
Spread operator is an ES6 feature which can also be used to read arguments from JavaScript functions. The syntax for spread operator is three dots
// syntax for rest operator
...
Let’s see how you can use to read arguments.
function takeParam(...args) {
console.log('Parameters list is ', args)
}
takeParam(1,2,3,4,5)
As you can see when using the Rest ES6 operator the arguments are converted into a array of arguments.
// console output is
"Parameters list is " [1, 2, 3, 4, 5]
Wrapping It Up
In this tutorial, you learnt about two ways to read arguments from JavaScript functions. Do let us know about any other method using which you can read arguments from JavaScript functions.