Default Parameters
Default Parameters
Section titled “Default Parameters”Introduction
Section titled “Introduction”Default parameters allow you to specify default values for function parameters. If an argument is undefined, the default value is used.
Syntax
Section titled “Syntax”function greet(name = 'Guest') { return `Hello, ${name}!`;}Example
Section titled “Example”function multiply(a, b = 1) { return a * b;}
console.log(multiply(5, 2)); // 10console.log(multiply(5)); // 5 (b defaults to 1)Defaults Can Be Expressions
Section titled “Defaults Can Be Expressions”function createElement(type = 'div', content = getDefaultContent()) { // ...}
function getDefaultContent() { return 'Default content';}Important Notes
Section titled “Important Notes”// Defaults only apply for undefined, NOT for nullfunction greet(name = 'Guest') { return `Hello, ${name}!`;}
greet(undefined); // 'Hello, Guest!'greet(null); // 'Hello, null!'Summary
Section titled “Summary”- Default parameters use
=in function signatures - Only trigger for
undefinedarguments - Can be expressions or function calls
- Make functions more flexible and safer