- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Default Parameters
Initialization:
- Before ES6, developers had to use logical operators (like
||) inside the function body to check if a value was provided. Default parameters modernize this by allowing you to initialize function parameters with default values directly in the function signature. - These values are used if no argument is passed or if an
undefinedvalue is explicitly passed during the function call.
Developer Tip: Default parameters are only triggered by
undefined. If you pass null, false, or 0, the default value will not be used because these are considered valid (falsy) values in JavaScript.
Syntax:
- Defining a default parameter is straightforward: use the assignment operator (=) followed by the value you want to use as a fallback in the function declaration.
Best Practice: Use default parameters to make your functions more robust. They act as a form of documentation, showing other developers what kind of data the function expects.
Example: Basic Usage
In this example, the name parameter defaults to 'Guest' if the caller doesn't provide a string.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!
greet(undefined); // Output: Hello, Guest! (undefined triggers the default)
Watch Out: Passing
null is a common way to accidentally bypass a default value.
greet(null); // Output: Hello, null! (The default was NOT used)
Example: Default Parameter with Expression
Default values aren't limited to static strings or numbers. You can use mathematical expressions or even call other functions to determine a default value at runtime.
function calculateArea(radius, pi = 3.14) {
return pi * radius * radius;
}
console.log(calculateArea(10)); // Uses 3.14
console.log(calculateArea(10, 3.14159)); // Overrides with a more precise value
Developer Tip: The default expression is evaluated at call time, not when the function is defined. This means if you use a function as a default value, it will run every time the main function is called without that argument.
Example: Default Parameters and Destructuring
This is a powerful pattern often used for configuration objects or API responses. You can combine destructuring with default values to handle deeply nested or missing properties gracefully.
function createUser({ username = 'anonymous', isAdmin = false, theme = 'dark' } = {}) {
console.log(`User: ${username}, Admin: ${isAdmin}, Theme: ${theme}`);
}
createUser({ username: 'dev_user' }); // Output: User: dev_user, Admin: false, Theme: dark
createUser(); // Output: User: anonymous, Admin: false, Theme: dark
Common Mistake: Forgetting the empty object default (
= {}) at the end of a destructured parameter list. Without it, calling createUser() (with no arguments) would throw an error because you cannot destructure properties from undefined.
No TDZ Issue:
- Parameters in JavaScript are evaluated from left to right. This means a parameter can reference any parameter declared before it without causing a Temporal Dead Zone (TDZ) error.
function multiply(a, b = a * 2) {
return a * b;
}
console.log(multiply(5)); // Output: 50 (5 * 10)
Order of Parameters:
- Technically, you can place default parameters anywhere in the list. However, for practical usage, they should be declared after your required parameters.
Example: Order of Parameters
// Hard to use: you must pass 'undefined' to skip 'b'
function badExample(a = 10, b) {
return a + b;
}
// Recommended:
function goodExample(b, a = 10) {
return a + b;
}
Best Practice: Always place your optional (default) parameters at the end of the parameter list. This allows callers to simply omit them rather than having to explicitly pass
undefined to reach later arguments.
Key Points
- Graceful Fallbacks: Default parameters provide a clean, native way to handle missing or
undefinedarguments. - Readability: They move logic out of the function body and into the signature, making the code easier to scan.
- Evaluation: Default values are computed at runtime, allowing for dynamic defaults based on other parameters or function calls.
- Integration: They work seamlessly with destructuring, making them ideal for handling complex settings and options objects.