JavaScript Function Parameters
14 April 2025 | Category: JavaScript
In JavaScript, function parameters are the named variables listed in the function definition. They act as placeholders for the values (called arguments) that will be passed into the function when it’s invoked.
đ§± Basic Syntax
function greet(name) {
console.log(`Hello, ${name}`);
}
Here, name
is a parameter. When calling greet("Alice")
, "Alice"
is the argument passed to the function.
đ§ Multiple Parameters
You can define multiple parameters separated by commas:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
âïž Default Parameters (ES6)
You can assign default values to parameters in case no argument is passed:
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
greet("Sam"); // Hello, Sam
đŠ Rest Parameters (...
)
When you want to pass an unknown number of arguments, use the rest parameter syntax (...
):
function sumAll(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sumAll(1, 2, 3, 4)); // 10
đč It gathers all remaining arguments into an array.
đ Arguments Object (Old Way)
Every non-arrow function gets a built-in arguments
object:
function showAll() {
console.log(arguments);
}
showAll(1, 2, 3); // [1, 2, 3]
â ïž Note:
arguments
is array-like, not a real array- Not available in arrow functions
đĄ Destructuring Parameters
You can extract values from objects or arrays directly in the parameter list.
â Object Destructuring:
function displayUser({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
displayUser({ name: "John", age: 30 });
â Array Destructuring:
function sum([a, b]) {
return a + b;
}
console.log(sum([3, 7])); // 10
â Summary
Feature | Description |
---|---|
Regular Parameters | Named variables in function definition |
Default Parameters | Provide fallback values if no argument is passed |
Rest Parameters | Capture multiple arguments into a single array |
arguments Object | Legacy method to access passed values (not in arrow funcs) |
Destructuring | Extract values from arrays/objects right in parameters |
đ Example Combining All Concepts
function introduce({ name = "Guest", age = 0 }, ...skills) {
console.log(`${name} is ${age} years old.`);
console.log("Skills:", skills.join(", "));
}
introduce({ name: "Alice", age: 25 }, "JavaScript", "React", "CSS");