Function parameters are placeholders in a function's definition that allow you to pass values into the function when it's called. They enable you to make functions more flexible and versatile by allowing them to work with different input values.
Function parameters are declared within the parentheses of a function's definition. They act as variables that receive values when the function is invoked.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
Arguments are the actual values passed into a function when it's called. They correspond to the function's parameters based on their position.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // "Alice" is the argument passed to the 'name' parameter
Functions can have multiple parameters, allowing you to pass in multiple values.
function add(a, b) {
return a + b;
}
var sum = add(5, 3); // sum is 8
ES6 introduced default parameter values that are used if an argument is not provided when the function is called.
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
Rest parameters allow you to pass an arbitrary number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
var total = sum(1, 2, 3, 4); // total is 10
function printInfo(firstName, lastName, ...otherInfo) {
console.log(`Name: ${firstName} ${lastName}`);
console.log(`Other info: ${otherInfo.join(', ')}`);
}
printInfo('John', 'Doe', 'Age: 30', 'Occupation: Developer');
function sum(...numbers) {
let result = 0;
for (let num of numbers) {
result += num;
}
return result;
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
The arguments object is an array-like object available within functions that holds all the arguments passed to the function.
function displayArguments() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
displayArguments(1, "hello", true);
// Outputs: 1
// hello
// true
Function parameters allow you to pass values into functions, enabling them to work with different inputs and enhancing the flexibility of your code.