β 1. What Are Function Parameters?
- Parameters are placeholders in a function definition.
- Arguments are the actual values passed to the function when it’s called.
jsCopyEditfunction greet(name) { // 'name' is a parameter
console.log("Hello, " + name);
}
greet("Alice"); // "Alice" is an argument
π 2. Multiple Parameters
You can pass multiple values:
jsCopyEditfunction add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
π 3. Default Parameters (ES6)
Provide default values in case arguments are missing:
jsCopyEditfunction greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Hello, Guest
greet("Sam"); // Hello, Sam
π 4. Rest Parameters (...args
)
Use this when you donβt know how many arguments will be passed.
jsCopyEditfunction sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
...args
turns all arguments into an array.
π 5. Arguments Object (Old Way)
All non-arrow functions have access to the special arguments
object.
jsCopyEditfunction showArgs() {
console.log(arguments);
}
showArgs(1, 2, 3); // [Arguments] { '0': 1, '1': 2, '2': 3 }
β οΈ Not available in arrow functions.
π 6. Destructuring Parameters
You can unpack objects or arrays in function parameters.
a. Object Destructuring
jsCopyEditfunction displayUser({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
displayUser({ name: "Alice", age: 25 }); // Alice is 25 years old.
b. Array Destructuring
jsCopyEditfunction printFirstTwo([first, second]) {
console.log(first, second);
}
printFirstTwo([10, 20, 30]); // 10 20
π 7. Named vs Positional Parameters
- Positional parameters rely on the order of arguments.
- Named parameters (via objects) improve clarity and flexibility.
jsCopyEditfunction createUser({ name, age }) {
return `${name} (${age})`;
}
console.log(createUser({ age: 30, name: "Tom" })); // Tom (30)
π 8. Combining All Types
jsCopyEditfunction userInfo(name = "Guest", ...roles) {
console.log(`Name: ${name}`);
console.log(`Roles: ${roles.join(", ")}`);
}
userInfo("Alice", "admin", "editor");
// Name: Alice
// Roles: admin, editor
π§ͺ Practice Challenges
- Create a function
greet(name = "Friend")
that returnsHello, <name>!
- Write a
sumAll(...nums)
that sums any number of arguments. - Write a function that destructures an object like
{ title, year }
.
π§ Summary Table
Feature | Syntax | Notes |
---|---|---|
Default Values | function greet(name = "Guest") | Sets fallback value |
Rest Parameters | function sum(...nums) | Gathers arguments into an array |
Arguments Object | arguments[i] | Old-school way, not for arrow funcs |
Destructuring | function show({id, name}) | Unpacks properties from objects |
π Bonus Tip
In arrow functions, you cannot use arguments
, but you can use rest parameters:
jsCopyEditconst sum = (...nums) => nums.reduce((a, b) => a + b);
Would you like this tutorial as a:
- π Downloadable PDF?
- π» Live code playground?
- π§ Quiz or flashcard set?