Functions in JavaScript: Default Parameters
Quick Answer
Default parameters in JavaScript allow you to specify default values for function parameters. If no argument or undefined is passed, the default value is used. This feature simplifies function definitions and avoids manual checks for missing arguments.
Learning Objectives
- Explain the purpose of Default Parameters in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Default Parameters.
- Apply Default Parameters in a simple real-world scenario or practice task.
Introduction
Functions are fundamental building blocks in JavaScript. They allow you to encapsulate reusable code.
Default parameters provide a way to assign default values to function parameters if no value or undefined is passed.
This feature was introduced in ES6 and helps write cleaner and more readable code.
A function should do one thing well, and default parameters help it handle missing inputs gracefully.
What Are Default Parameters?
Default parameters let you specify a default value for a function parameter directly in the function signature.
If the caller does not provide a value or explicitly passes undefined, the default value is used instead.
- Introduced in ES6 (ECMAScript 2015).
- Simplifies handling of optional parameters.
- Avoids manual checks inside the function body.
Syntax and Usage
You define default parameters by assigning a value to the parameter in the function declaration.
For example, function greet(name = 'Guest') { ... } sets 'Guest' as the default if no argument is passed.
- Default values can be any valid expression.
- Parameters with defaults should typically come after required parameters.
Examples of Default Parameters
Here are some practical examples demonstrating default parameters in action.
Basic Greeting Function
This function greets a user by name, defaulting to 'Guest' if no name is provided.
Multiple Default Parameters
Functions can have multiple parameters with default values, allowing flexible calls.
Best Practices for Using Default Parameters
Using default parameters effectively can improve code readability and reduce bugs.
- Place parameters with defaults after required parameters.
- Use simple expressions for default values to avoid side effects.
- Avoid complex logic inside default parameter expressions.
- Use default parameters instead of manual checks for undefined.
Common Mistakes with Default Parameters
Be aware of common pitfalls when using default parameters.
- Passing null does not trigger the default value; only undefined does.
- Default parameters are evaluated at call time, so avoid using mutable objects as defaults.
- Incorrect parameter order can cause unexpected behavior.
Practical Example
This example shows a function greet with a default parameter 'Guest'. If no argument is passed, it uses the default.
This function demonstrates multiple default parameters for flexible user creation.
Examples
function greet(name = 'Guest') {
console.log('Hello, ' + name + '!');
}
greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!This example shows a function greet with a default parameter 'Guest'. If no argument is passed, it uses the default.
function createUser(name = 'Anonymous', age = 18) {
return { name, age };
}
console.log(createUser()); // { name: 'Anonymous', age: 18 }
console.log(createUser('Bob', 25)); // { name: 'Bob', age: 25 }This function demonstrates multiple default parameters for flexible user creation.
Best Practices
- Always place parameters with default values after required parameters.
- Use default parameters to simplify function logic and avoid manual undefined checks.
- Keep default parameter expressions simple and free of side effects.
- Test functions with and without arguments to ensure defaults work as expected.
Common Mistakes
- Assuming null triggers default parameters; only undefined does.
- Using mutable objects like arrays or objects as default parameters, which can lead to shared state bugs.
- Placing default parameters before required ones, causing unexpected undefined values.
- Overcomplicating default parameter expressions leading to hard-to-debug code.
Hands-on Exercise
Create a Function with Default Parameters
Write a function that calculates the total price with a default tax rate of 5%. Allow overriding the tax rate.
Expected output: Function returns the total price including tax, using the default tax rate if none is provided.
Hint: Use a default parameter for the tax rate in the function signature.
Test Default Parameters Behavior
Write a function with a default parameter and test it by passing undefined, null, and no argument. Observe the results.
Expected output: Function uses default value when argument is undefined or missing, but uses passed value when null is passed.
Hint: Remember that only undefined triggers the default value.
Interview Questions
What happens if you pass null to a function parameter that has a default value?
InterviewPassing null does not trigger the default parameter; the parameter receives null as its value.
How do default parameters improve JavaScript function definitions?
InterviewDefault parameters allow setting fallback values directly in the function signature, reducing the need for manual checks and making code cleaner and more readable.
What is Default Parameters, and why is it useful?
BeginnerDefault parameters in JavaScript allow you to specify default values for function parameters.
MCQ Quiz
1. What is the best first step when learning Default Parameters?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Default Parameters?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Default parameters in JavaScript allow you to specify default values for function parameters.
B. Default Parameters never needs examples
C. Default Parameters is unrelated to practical work
D. Default Parameters should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Default parameters in JavaScript allow you to specify default values for function parameters.
- If no argument or undefined is passed, the default value is used.
- This feature simplifies function definitions and avoids manual checks for missing arguments.
- Functions are fundamental building blocks in JavaScript.
- They allow you to encapsulate reusable code.
Summary
Default parameters in JavaScript provide a clean way to assign fallback values to function parameters.
They help avoid manual checks for undefined and make functions more flexible and readable.
Understanding how default parameters work, including their evaluation and common pitfalls, is essential for writing robust JavaScript code.
Frequently Asked Questions
When were default parameters introduced in JavaScript?
Default parameters were introduced in ES6 (ECMAScript 2015).
Do default parameters get used if null is passed as an argument?
No, default parameters are only used if the argument is undefined or missing, not if null is passed.
Can default parameters be expressions or function calls?
Yes, default parameters can be any valid expression, including function calls, but it's best to keep them simple to avoid side effects.


