JavaScript Function Parameters
Function parameters are variables used to pass data into functions. JavaScript functions can accept any number of parameters, which are specified inside parentheses during function definition.
Key Topics
Basic Parameters
Basic parameters allow you to pass values to a function for processing.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
Output
> Hello, Alice!
Explanation: The greet
function takes a single parameter name
and uses it to construct a personalized greeting message.
Default Parameters
Default parameters allow you to set a default value for a parameter if no value is provided when the function is called.
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet();
Output
> Hello, Guest!
Explanation: If the greet
function is called without an argument, the default value Guest
is used.
Rest Parameters
Rest parameters allow you to pass an indefinite number of arguments to a function, which are captured as an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log("Total: ", sum(1, 2, 3, 4));
Output
> Total: 10
Explanation: The sum
function collects all arguments passed to it into the numbers
array and calculates their total using the reduce
method.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating the use of function parameters to dynamically update content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Function Parameters in DOM</title>
</head>
<body>
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="displayGreeting()">Greet</button>
<p id="greeting"></p>
<script>
function displayGreeting() {
const name = document.getElementById("nameInput").value || "Guest";
document.getElementById("greeting").textContent = `Hello, ${name}!`;
}
</script>
</body>
</html>
Key Takeaways
- Basic Parameters: Pass values to functions for processing.
- Default Parameters: Set default values to avoid undefined behavior.
- Rest Parameters: Handle variable-length argument lists easily.
- DOM Integration: Use parameters to dynamically update UI elements based on user input.