Passing Arguments to JavaScript Functions
In JavaScript, functions can accept arguments, which are values that are passed to the function when it is called. These arguments can be used within the function to perform various operations or calculations. Here's how you can pass arguments to JavaScript functions:
Defining Function Parameters
When defining a function, you can specify the parameters it will accept within the function's parentheses. These parameters act as placeholders for the values that will be passed to the function when it is called.
Here's an example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
In this example, the greet
function has a single parameter called name
. When the function is called, the value passed for name
will be used within the function.
Calling Functions with Arguments
To call a function and pass arguments, you simply need to provide the values within the function call's parentheses, separated by commas if there are multiple arguments.
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
In this example, the greet
function is called twice, each time with a different value passed for the name
parameter.
Multiple Parameters
Functions can accept multiple parameters, which are separated by commas in the function definition and function call.
function calculateArea(width, height) {
return width * height;
}
const area = calculateArea(5, 10);
console.log(area); // Output: 50
In this example, the calculateArea
function has two parameters, width
and height
, and the function call passes two arguments, 5
and 10
, which are used to calculate the area.
Default Parameters
JavaScript also allows you to define default values for function parameters, which are used if no argument is provided when the function is called.
function greetWithDefault(name = "stranger") {
console.log(`Hello, ${name}!`);
}
greetWithDefault(); // Output: Hello, stranger!
greetWithDefault("Alice"); // Output: Hello, Alice!
In this example, the greetWithDefault
function has a default parameter value of "stranger"
for the name
parameter. If no argument is provided when the function is called, the default value is used.
Mermaid Diagram: Function Parameters
Here's a Mermaid diagram that illustrates the concept of function parameters in JavaScript:
This diagram shows the relationship between function definition, function parameters (including default parameters and multiple parameters), and function calls with arguments.
In summary, passing arguments to JavaScript functions is a fundamental concept that allows you to make your functions more flexible and reusable. By defining parameters and passing arguments, you can create functions that can perform different tasks or calculations based on the values provided when the function is called.