This tutorial aims to provide a detailed understanding of function parameters in JavaScript. Function parameters make your code more dynamic and flexible by allowing functions to operate on different inputs.
By the end of this tutorial, you will be able to:
- Understand what function parameters are
- Create and use function parameters in your own JavaScript code
- Understand the difference between parameters and arguments
Prerequisites: Basic understanding of JavaScript syntax, specifically functions.
In JavaScript, a function parameter is a named variable that is passed into a function. When a function is invoked, you pass an argument to the function, and this argument is received by the function as a parameter.
Here's a simple example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice");
In this code, name
is the parameter of the function greet
. When we call the function with greet("Alice")
, "Alice"
is the argument that we pass to the function.
Here's an example of a function with two parameters:
// A function with two parameters
function add(num1, num2) {
let result = num1 + num2;
console.log(result);
}
add(10, 20); // Expected output: 30
JavaScript functions can also have default parameters.
// A function with a default parameter
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet("Alice"); // Outputs: Hello, Alice
greet(); // Outputs: Hello, Guest
In this tutorial, you learned about function parameters in JavaScript. You now know how to create functions with parameters, use default parameters, and understand the difference between parameters and arguments.
Next, you might want to learn about more complex topics like closures or recursion in JavaScript. Some resources for further learning include the Mozilla Developer Network (MDN) JavaScript Guide and the book "You Don't Know JS" by Kyle Simpson.
Create a function that multiplies three numbers.
Create a function with a default parameter.
Create a function that calculates the area of a rectangle.
Exercise 1
function multiply(a, b, c) {
return a * b * c;
}
console.log(multiply(2, 3, 4)); // Outputs: 24
Exercise 2
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet("Alice"); // Outputs: Hello, Alice
greet(); // Outputs: Hello, Guest
Exercise 3
function area(length, width) {
return length * width;
}
console.log(area(5, 7)); // Outputs: 35
Keep practicing with different parameter configurations and function structures to get a solid understanding of this concept. Enjoy coding!