Hide/Show table of contents
| No. | Questions |
|---|---|
| Core JS | |
| 1 | What is arguments in JavaScript? |
| 2 | What is the role of the Arguments Object in JavaScript Functions? |
-
The arguments is an object which is local to a function. You can think of it as a local variable that is available with all functions by default except arrow functions in JavaScript.
This object (arguments) is used to access the parameter passed to a function. It is only available within a function. We can’t access it outside the function. Arguments object allow you to access all of the arguments that are passed to a function. We can access these arguments using indexes.
Example-1
Output: Hello!
Example-2
Output: undefined
Example-3 : Programs using arguments object.
Output: 6
As we have discussed earlier arguments object is local to a function that is used to access the parameters passed to it. Since we are passing n=3 as a parameter. So inside the arguments object, we have only one variable that is 3. And n=3 because we are passing value 3 to func function. So arguments[0]=3 (this arguments is not outside array, but it is arguments object which is local to any non-arrow function) and n=3.
Example - 4: Finding the length of the parameters using the arguments object.
Output: Length is: 5
Example:5 Finding the sum of the parameters passed to a function using the arguments object.
Output: Sum is :15 -
The arguments object provides a way to access these arguments dynamically, even if the function is not defined with specific parameter names. Simply, it lets you access the values passed to a function, even if you didn’t define them as parameters.
Example: Here, the sum() function does not have any declared parameters. Inside the function body, we access the arguments passed to the function using the arguments object.