
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Passing unknown number of arguments to a function in Javascript
When you call a function in JavaScript you can pass in any number of arguments. There is no function parameter limit. This also means that functions can't be overloaded in traditional ways in js.
The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.
For example, if a function is passed 3 arguments, you can access them as follows −
arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument
Note − arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map().
For example, to accept a arbitrary number of args, you can create a function as follows −
Example
function printAllArguments(a, b) { console.log("First arg: " + a) console.log("Second arg: " + b) console.log("All args: " + arguments) } printAllArguments(1) printAllArguments(1, "hello") printAllArguments(1, "hello", 1, "hello")
Output
First arg: 1 Second arg: undefined All args: {"0":1} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello"} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello","2":1,"3":"hello"}
- Related Questions & Answers
- Passing Arguments to a Subroutine in Perl
- How to use variable number of arguments to function in JavaScript?
- Passing arguments to a Tkinter button command
- Passing a function as a callback in JavaScript
- What MySQL CONCAT() function returns by passing the numeric arguments?
- How to use unlimited arguments in a JavaScript function?
- How to check the least number of arguments a function expects in R?
- How can I find the number of arguments of a Python function?
- Passing static methods as arguments in PHP
- How to divide an unknown integer into a given number of even parts using JavaScript?
- How to pass arrays as function arguments in JavaScript?
- Passing an array to a C++ function
- Passing a 2D array to a C++ function
- Passing Arrays to Function in C++
- Function to compute factorial of a number in JavaScript