Conceptcore
Default value
Also called default value, default, zero value, default initialization, default parameter, default argument, fallback value, null default, undefined.
A default value is the value that a variable, a field or a parameter gets when the program gives none, such as 0, false or null. Some languages give one to each variable, and others only to fields.
- Applies to
- core-languages
Idea
A program often needs a value where nobody gave one: a field of a new object, a parameter that the caller left out, a key that is not in a map. A default value fills the gap. In general use, "A default, in computer science, refers to the preexisting value of a user-configurable setting"1, and "When programmers or users failed to provide a specific value or setting, the system would revert to a pre-programmed or standard value."1
In Python, a parameter and a map lookup can have a default value:
def greet(name="world"):
return "Hello, " + name
print(greet())
print(greet("Ada"))
settings = {"width": 80}
print(settings.get("height", 24))
Hello, world
Hello, Ada
24
How it works
Default values of variables. Some languages put a fixed value into each new variable that has no initializer, see Initialization. The value depends on the type, and it is the value with all bits zero in most cases. Go calls it the zero value: each element "is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps"2. Java gives default values to fields and array elements: "For type int, the default value is zero, that is, 0."3 "For type boolean, the default value is false."3 "For all reference types (§4.3), the default value is null."3 C# has a table of the same kind: "Any reference type null"4, and for a struct, "The value produced by setting all value-type fields to their default values and all reference-type fields to null."4
undefined in JavaScript. JavaScript has a special value for a variable with no value yet. "A variable that has not been assigned a value is of type undefined."5 The same value comes back from a missing property: "Accessing a property that does not exist also returns undefined."5
A default that the type defines. In Rust, a variable has no default value, but a type can have one. The trait Default is "A trait for giving a type a useful default value."6 #[derive(Default)] makes one for a struct, and "When derived, it will use the default value for each field’s type."6 C++ has default constructors and default member initializers for the same purpose.
Default parameters. A function can give a parameter a value for a call that leaves it out. "Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed."7 Python, JavaScript, TypeScript, Kotlin, C# and C++ have default parameters. Java, Go and C do not: the program uses overloads, a variadic parameter, or a struct of options.
Defaults for lookups. A map lookup for a missing key needs a value too. Python has dict.get(key, default) and collections.defaultdict, Java has getOrDefault, and a Go map gives the zero value of its value type.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has undefined, default parameters and the operator ?? of JavaScript, and marks an optional parameter or property with ?. No example file exists. |
| Go | Native | |
| Rust | Library | |
| Kotlin | Native | Kotlin gives no implicit default to a variable or a property, but a parameter can have a default value, and a property has an initializer. No example file exists because kotlinc is not installed. |
| SQL | Native | The DEFAULT clause of a column gives the value of a new row when the insert gives none. Without a default, the value is NULL. No example file exists. |
| Bash | Idiom | A variable that was never set expands to the empty string, and ${name:-default} gives a default for an unset or empty variable. No example file exists. |
| PowerShell | Idiom | A variable that was never assigned is $null, and a parameter of a function or a script can have a default value. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup, with no variables. The value attribute gives a form control its first value. |
| CSS | Native | Each property has an initial value in its definition, and an inherited property takes the value of the parent. No example file exists. |
| Regular expressions | Does not apply | A pattern has no variables. |
| Language | Verdict | Default value |
|---|---|---|
| Python | idiom | no default for variables; default parameters, dict.get, defaultdict and fields of a dataclass |
| JavaScript | native | undefined for a variable, a property or a parameter with no value; default parameters and ?? |
| TypeScript | native | the rules of JavaScript, and optional parameters and properties |
| Java | native | 0, false, '\u0000' or null for fields and array elements |
| Kotlin | native | no implicit default; default parameter values and property initializers |
| C# | native | default and default(T); 0, false or null for fields and array elements; default parameters |
| Go | native | the zero value of the type for each variable |
| Rust | library | no implicit default; the trait Default and #[derive(Default)] |
| C | native | zero for static objects and calloc; none for automatic variables |
| C++ | native | value initialization with {}, default constructors and default member initializers |
| Bash | idiom | an unset variable is empty; ${name:-default} gives a default |
| PowerShell | idiom | an unassigned variable is $null; default values for parameters |
| SQL | native | the DEFAULT clause of a column, else NULL |
| Regex | n/a | a pattern has no variables |
| HTML | n/a | HTML is markup, with no variables |
| CSS | native | each property has an initial value |
from collections import defaultdict
from dataclasses import dataclass, field
@dataclass
class Options:
width: int = 80
tags: list = field(default_factory=list)
print(Options())
print(Options(width=100))
counts = defaultdict(int)
counts["a"] += 1
print(counts["a"], counts["b"])
Options(width=80, tags=[])
Options(width=100, tags=[])
1 0
- Verdict: idiom. A Python variable has no default value: a name exists only after a binding. Defaults come from the program: a dataclass field with a default,
field(default_factory=list)for a new list on each object, anddefaultdict(int), which callsint()to make 0 for a missing key.
#include <iostream>
#include <map>
#include <string>
struct Options {
int width = 80;
bool verbose{};
std::string name;
};
int main() {
Options o;
std::cout << o.width << ' ' << o.verbose << " [" << o.name << "]\n";
std::map<std::string, int> counts;
counts["a"] += 1;
std::cout << counts["a"] << ' ' << counts["b"] << ' ' << counts.size() << '\n';
std::cout << int{} << ' ' << double{} << '\n';
}
80 0 []
1 0 2
0 0
- Verdict: native. A default member initializer such as
int width = 80;gives a field its value in each new object.{}gives the zero value of a built-in type.std::map::operator[]inserts a value-initialized element for a missing key, so the read ofcounts["b"]adds a key.
public class Main {
static byte smallNumber;
static double ratio;
static char letter;
static boolean flag;
static Object thing;
public static void main(String[] args) {
System.out.println(smallNumber + " " + ratio + " " + (int) letter + " " + flag + " " + thing);
String[] names = new String[2];
boolean[] seen = new boolean[2];
System.out.println(names[0] + " " + seen[1]);
}
}
0 0.0 0 false null
null false
- Verdict: native. Each field and each array element gets the default value of its type: zero for numbers, the character
'\u0000'forchar,falseforbooleanandnullfor references. Local variables get no default value: the compiler requires an assignment before a read.
#include <stdio.h>
#include <stdlib.h>
struct config {
int width;
double scale;
const char *name;
};
static struct config global;
int main(void) {
printf("%d %.1f %s\n", global.width, global.scale, global.name == NULL ? "NULL" : global.name);
int *counts = calloc(4, sizeof *counts);
if (counts == NULL) {
return 1;
}
printf("%d %d\n", counts[0], counts[3]);
free(counts);
struct config local = {0};
printf("%d %.1f\n", local.width, local.scale);
return 0;
}
0 0.0 NULL
0 0
0 0.0
- Verdict: native. A static object without an initializer is zero: numbers are 0 and pointers are null.
callocgives memory set to zero, butmallocdoes not. An automatic variable has no default value, and= {0}sets all the members of a local struct to zero.
using System;
Console.WriteLine($"{Zero<int>()} {Zero<string>() == null} {Zero<bool>()}");
int? maybe = default;
Console.WriteLine(maybe.HasValue);
var p = default(Point);
Console.WriteLine($"{p.X} {p.Y}");
Console.WriteLine($"{Label()} {Label("Ada")}");
static T? Zero<T>() => default;
static string Label(string name = "none") => name;
record struct Point(int X, int Y);
0 True False
False
0 0
none Ada
- Verdict: native.
defaultgives the default value of a type: 0,false,null, or a struct with each field set to its default. For a nullable value type, the default has no value. A parameter can have a default value, which the compiler puts into each call that leaves it out.
let x;
const obj = {};
console.log(x, obj.missing, [1, 2][5]);
function area(w, h = w) {
return w * h;
}
console.log(area(3), area(3, 4));
const count = 0;
console.log(count || 10, count ?? 10);
undefined undefined undefined
9 12
10 0
- Verdict: native.
undefinedis the default value of a variable, a missing property and an element past the end of an array. A default parameter can use an earlier parameter.||replaces any falsy value, so it replaces a count of 0, but??replaces onlynullandundefined.
package main
import (
"fmt"
"strings"
)
func main() {
var sb strings.Builder
sb.WriteString("ready")
fmt.Println(sb.String(), sb.Len())
var counts map[string]int
fmt.Println(counts["x"], len(counts))
var list []string
list = append(list, "a")
fmt.Println(list, len(list))
}
ready 5
0 0
[a] 1
- Verdict: native. Each variable starts at the zero value of its type, and many types work at their zero value: an empty
strings.Builderis ready, a nil map can be read, andappendto a nil slice makes a new slice. Go has no default parameters: a function takes a struct of options, and the zero value of each field means "use the default".
#[derive(Debug, Default)]
struct Options {
width: u32,
name: String,
verbose: bool,
}
fn main() {
let o = Options::default();
println!("{o:?}");
let p = Options {
width: 80,
..Default::default()
};
println!("{} {:?} {}", p.width, p.name, p.verbose);
let words: Vec<&str> = Vec::new();
println!("{}", words.first().copied().unwrap_or("none"));
}
Options { width: 0, name: "", verbose: false }
80 "" false
none
- Verdict: library. Rust gives no value to a variable without one. The trait
Defaultgives a type a default value, and#[derive(Default)]uses the default of each field...Default::default()fills the fields that a struct literal leaves out.unwrap_orgives a default for a missing value.
Variations and related ideas
- Zero values that work. In Go, a type can make its zero value ready to use: an empty
strings.Builderorbytes.Bufferneeds no constructor. - null and Option. A default of
nullmeans "no value", and a read of a field of it fails. Rust and other languages use an option type, and the program must say what to do when the value is missing. - Default arguments evaluated once or at each call. Python evaluates a default parameter once, when it defines the function. In JavaScript, "The default argument is evaluated at call time."7
- Configuration defaults. A program reads settings from a file or the command line, and a default for each missing setting.
Pitfalls
- A mutable default parameter in Python. "Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call."8 So a list as a default is shared by all calls:
This code runs but gives a wrong answer on purpose.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))
['a']
['a', 'b']
Write items=None and if items is None: items = [] in the body.
- A default that hides a bug. A zero value looks like real data. A count of 0 from a field that nobody set is wrong, but the program does not see it.
- 0 and false as a missing value.
value || fallbackin JavaScript replaces 0,""andfalsetoo. Usevalue ?? fallback, which replaces onlynullandundefined. - null as a default. A default of
nulldefers the error to the first use of the value.
Cost
A default value for each variable costs a write of zeros, which the program can do in bulk for an array or an object. A default parameter costs the evaluation of its expression on each call that leaves it out, or once in Python.
History
The word comes from the failure to make a choice: "This "failure" to explicitly define a choice led to that preset value being called the "default"."1 Java gave default values to fields and array elements, and Go extended the idea to each variable with the zero value.
References
- Default (computer science), Wikipedia, Introduction
- The Go Programming Language Specification, The zero value
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.5 Initial Values of Variables
- Default values of C# types, C# reference, Introduction
- undefined, MDN Web Docs, Description
- Trait Default, Rust standard library, Description; Derivable
- Default parameters, MDN Web Docs, Description; Evaluated at call time
- Compound statements, The Python Language Reference, 8.7 Function definitions
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 9A6ECK Edit this page History Report an error Markdown