Function Parameters in JavaScript
? Function Parameters in JavaScript
What are Function Parameters?
Parameters are named variables in a function definition that receive values when the function is called.
They allow passing data into functions.
Types of Parameters
1. Regular Parameters
function greet(name) { console.log("Hello, " + name);}greet("Alice"); // Output: Hello, Alice2. Default Parameters (ES6+)
Parameters can have default values if no argument or
undefinedis passed.
function greet(name = "Guest") { console.log("Hello, " + name);}greet(); // Hello, Guestgreet("Alice"); // Hello, Alice3. Rest Parameters (ES6+)
Collects all remaining arguments into an array.
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0);}console.log(sum(1, 2, 3)); // 6console.log(sum(4, 5)); // 94. Arguments Object (Old Style)
Inside non-arrow functions, you can access
arguments— an array-like object of all passed arguments.
function showArgs() { console.log(arguments);}showArgs(1, 2, 3); // Outputs: Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]Not available in arrow functions.
Parameter vs Argument
| Term | Meaning |
|---|---|
| Parameter | Named variable in function definition |
| Argument | Actual value passed when calling function |
Example Combining Features
function describe(name = "Unknown", age = 0, ...hobbies) { console.log(`${name} is ${age} years old.`); console.log("Hobbies:", hobbies.join(", "));}describe("Alice", 25, "Reading", "Hiking", "Coding");Summary Table
| Feature | Description | Syntax Example |
|---|---|---|
| Default Parameters | Default values if no argument | function f(a=1) {} |
| Rest Parameters | Collects remaining args into array | function f(...args) {} |
| Arguments Object | Array-like of all arguments | arguments inside function |
Want examples of destructuring parameters or how to handle optional parameters cleanly?