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__.