JavaScript Function Parameters
JavaScript function parameters allow you to pass data into functions, making them dynamic, reusable, and powerful.
1. Basic Parameters
Function parameters are defined in the function declaration. When calling the function, you pass arguments.
Example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice");
Output
Hello, Alice
2. Multiple Parameters
You can define more than one parameter.
Example:
function add(a, b) {
console.log("Sum:", a + b);
}
add(5, 10);
Output
Sum: 15
3. Default Parameters (ES6+)
Default values can be set for parameters to avoid undefined.
Example:
function greet(name = "Guest") {
console.log("Welcome, " + name);
}
greet(); // Uses default
greet("John"); // Uses provided value
Output
Welcome, Guest
Welcome, John
Welcome, John
4. Rest Parameters (...)
Use rest parameters to pass any number of arguments. They are gathered into an array.
Example:
function sumAll(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sumAll(1, 2, 3, 4, 5));
Output
15
5. Parameter Destructuring
You can extract object or array properties directly in the parameter list.
Example (Object Destructuring):
function printUser({ name, age }) {
console.log(name + " is " + age + " years old.");
}
printUser({ name: "Emma", age: 30 });
Output
Emma is 30 years old.
6. Arguments Object (Legacy Way)
Inside regular functions, arguments is an array-like object containing all passed arguments.
Example:
function showArgs() {
console.log(arguments);
}
showArgs(1, 2, 3);
Output
[Arguments] { '0': 1, '1': 2, '2': 3 }
Summary Table – JavaScript Function Parameter Types
Type | Syntax Example | Use Case |
---|---|---|
Basic | function greet(name) | One or more fixed parameters |
Default | function greet(name = "Guest") | Fallback value |
Rest (...) | function sum(...nums) | Accept any number of arguments |
Destructuring | function show({name, age}) | Directly extract from object/array |
Arguments object | function test() { console.log(arguments) } | Capture all args in regular functions |