Default argument

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Default Parameters

JS · Functions
Syntax
function fn(param = defaultValue) {}
Example
function fetchData(url, options = {}) {
  const { method = "GET", timeout = 3000 } = options;
  console.log(`${method} ${url} (timeout: ${timeout}ms)`);
}
fetchData("/api/users");
fetchData("/api/users", { method: "POST" });
Output
"GET /api/users (timeout: 3000ms)"
"POST /api/users (timeout: 3000ms)"

Note Defaults are evaluated at call time, not definition time. Each call creates a fresh default value, so objects/arrays as defaults are safe.

PYPython

Defining Functions

PY · Functions
Syntax
def name(params):
    """docstring"""
    return value
Example
def greet(name: str, greeting: str = "Hello") -> str:
    """Build a personalized greeting."""
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", greeting="Hey"))
Output
Hello, Alice!
Hey, Bob!

Note Functions without an explicit return statement return None. Docstrings are accessible via help(func) and func.__doc__.

Frequently asked questions

How does JavaScript handle default argument?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Default Parameters" snippet in JavaScript uses `function fn(param = defaultValue) {}`.
Which code does the JavaScript example use?
The "Default Parameters" snippet uses `function fn(param = defaultValue) {}`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "default argument" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Default Parameters": Defaults are evaluated at call time, not definition time. Each call creates a fresh default value, so objects/arrays as defaults are safe.