Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Parameters are named variables in a function that receive values when the function is called. Think of them as labeled containers that hold the data your function needs.
When you define a function, you specify parameters. When you call it, you pass arguments.
// Parameters: name, age
function introduce(name, age) {
return 'I am ' + name + ', ' + age + ' years old';
}
// Arguments: 'Alice', 25
const message = introduce('Alice', 25);
console.log(message);
// Output: I am Alice, 25 years oldPass different values to the same function
Default parameters let you set fallback values. If someone doesn't pass an argument, the default kicks in automatically!
function greet(name) {
console.log('Hello, ' + name);
}
greet();
// Output: Hello, undefined
// Not good! ❌function greet(name = 'Guest') {
console.log('Hello, ' + name);
}
greet();
// Output: Hello, Guest
// Perfect! ✅Set default values for optional parameters
Defaults can be any expression, not just simple values
undefined. Passing null or 0 will NOT trigger the default!The rest parameter syntax ...name collects all remaining arguments into an array. Perfect for flexible functions!
function sum(...numbers) {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2)); // 3
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum()); // 0
// numbers becomes an array!Combine fixed parameters with rest parameters
...restInstead of passing an entire object and accessing properties inside, you can destructure right in the parameter list!
function displayUser(user) {
return user.name +
' (' + user.email + ')';
}
// Have to repeat 'user.'function displayUser({ name, email }) {
return name + ' (' + email + ')';
}
// Much cleaner! ✅Combine destructuring with default values
Extract array elements by position
Instead of many individual parameters, pass a single options object with defaults. This pattern is used everywhere in modern JavaScript!
// Options object with destructuring + defaults
function createButton({
text,
color = 'blue',
size = 'medium',
disabled = false
}) {
return 'Button: ' + text +
' (' + color + ', ' + size + ')';
}
// Only pass what you need!
const btn = createButton({
text: 'Click Me',
color: 'red'
});
console.log(btn);
// Output: Button: Click Me (red, medium)Accept unlimited arguments for calculations