What are Variadic functions?
Variadic functions are functions that accept a variable number of arguments. This allows you to pass any number of parameters when calling the function.
📌 In JavaScript:
JavaScript supports variadic functions using the rest parameter (...
) or the special object arguments
.
1. Using Rest Parameter (...
)
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(5, 10, 15, 20)); // Output: 50
...numbers
collects all arguments into an array.
2. Using arguments
Object (older method)
function multiply() {
let result = 1;
for (let i = 0; i < arguments.length; i++) {
result *= arguments[i];
}
return result;
}
console.log(multiply(2, 3, 4)); // Output: 24
arguments
is array-like but not a true array.
📌 In Python:
Python uses *args
for positional arguments and **kwargs
for keyword arguments.
Example:
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!
📌 In C/C++:
C/C++ uses stdarg.h
for variadic functions.
Example:
#include <stdio.h>
#include <stdarg.h>
void printNumbers(int count, ...) {
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
printf("%d ", va_arg(args, int));
}
va_end(args);
printf("\n");
}
int main() {
printNumbers(3, 10, 20, 30); // Output: 10 20 30
return 0;
}
✅ Summary:
- Variadic functions allow flexibility by accepting multiple arguments.
- In modern JavaScript, the rest parameter (
...args
) is the preferred method.
Comments
Post a Comment
Write something to CodeWithAbdur!