Function parameters are the names listed in a function's definition, allowing you to pass data into the function. They act as placeholders for values that will be provided when the function is called.
In JavaScript, you define function parameters within parentheses after the function name:
function functionName(parameter1, parameter2) {
// Function body
}
Parameters enable functions to work with different inputs. Here's a simple example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
JavaScript allows you to set default values for parameters. These values are used when an argument is not provided or is undefined
.
function greetWithDefault(name = "Guest") {
console.log("Welcome, " + name + "!");
}
greetWithDefault(); // Output: Welcome, Guest!
greetWithDefault("Alice"); // Output: Welcome, Alice!
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. It's denoted by three dots (...) followed by the parameter name:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
You can use destructuring in function parameters to extract values from objects or arrays passed as arguments:
function printUserInfo({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
const user = { name: "Alice", age: 30, country: "USA" };
printUserInfo(user); // Output: Name: Alice, Age: 30
To deepen your understanding of JavaScript functions, explore these related topics:
By mastering function parameters, you'll be able to create more flexible and reusable JavaScript code. Practice with different parameter types and experiment with various function designs to enhance your programming skills.