Lesson 14 - Default Parameters in JavaScript
We saw in lessons 11 that we could create a function and pass in its brackets a value that it will use in its logic.And we also saw in lesson 12 that we could pass in the values a
and b
to the add
function.
These values we pass to the function to use in its logic are called parameters. So it may happen that, in the function's logic, we want to make use of those paramters or not. For example in the case of greet(name)
we may want to just say Hello
without adding a name, or in case we don't have the user's name, we write Hello, guest
. In this case, the guest value becomes what we call the default function parameter.
So, let's see how Javascript handles that in practice.
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!
Explanation:
- Default parameters allow functions to have a fallback value if no argument is provided.
- In function
greet(name = "Guest")
, if no name is given, "Guest" is used greet("Alice")
prints "Hello, Alice!", whilegreet()
prints "Hello, Guest!".
Try your hand:
1. Create a File:
Create a new file namedlesson14-default-parameters.html
.
2. Write the Code:
Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 14 - Default Parameters</title>
</head>
<body>
<script>
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!
</script>
</body>
</html>
Save the file in your folder.
3. Preview the File:
-
Open the file in your browser and access the developer console.
-
Observe the output:
Hello, Alice! Hello, Guest!
4. Experiment:
-
Try changing the default parameter value from
"Guest"
to"User"
and observe the change. -
Use an arrow function with a default parameter:
const multiply = (a, b = 2) => a * b;
console.log(multiply(5)); // Output: 10 (5 * 2)
console.log(multiply(5, 3)); // Output: 15 (5 * 3)
- Use multiple default parameters:
function introduce(name = "Guest", age = 18) {
console.log(`My name is ${name} and I am ${age} years old.`);
}
introduce(); // Output: My name is Guest and I am 18 years old.
introduce("John", 25); // Output: My name is John and I am 25 years old.