|
| 1 | +--- |
| 2 | +id: "optional-labeled-argument" |
| 3 | +keywords: ["optional", "labeled", "argument"] |
| 4 | +name: "~arg=?" |
| 5 | +summary: "This is an `optional labeled argument`." |
| 6 | +category: "languageconstructs" |
| 7 | +--- |
| 8 | + |
| 9 | +Labeled arguments, i.e. arguments that are prefixed with `~`, can be suffixed with `=?` to denote that they are optional. Thus, they can be |
| 10 | +omitted when calling the function. |
| 11 | + |
| 12 | +### Example |
| 13 | + |
| 14 | +<CodeTab labels={["ReScript", "JS Output"]}> |
| 15 | + |
| 16 | +```res example |
| 17 | +let print = (text, ~logLevel=?) => { |
| 18 | + switch logLevel { |
| 19 | + | Some(#error) => Console.error(text) |
| 20 | + | _ => Console.log(text) |
| 21 | + } |
| 22 | +} |
| 23 | +
|
| 24 | +print("An info") |
| 25 | +print("An error", ~logLevel=#error) |
| 26 | +``` |
| 27 | + |
| 28 | +```js |
| 29 | +function print(text, logLevel) { |
| 30 | + if (logLevel === "error") { |
| 31 | + console.error(text); |
| 32 | + } else { |
| 33 | + console.log(text); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +print("An info", undefined); |
| 38 | + |
| 39 | +print("An error", "error"); |
| 40 | +``` |
| 41 | + |
| 42 | +</CodeTab> |
| 43 | + |
| 44 | +Optional labeled arguments can also hold a default value. |
| 45 | + |
| 46 | +<CodeTab labels={["ReScript", "JS Output"]}> |
| 47 | + |
| 48 | +```res example |
| 49 | +let print = (text, ~logLevel=#info) => { |
| 50 | + switch logLevel { |
| 51 | + | #error => Console.error(text) |
| 52 | + | #warn => Console.warn(text) |
| 53 | + | #info => Console.log(text) |
| 54 | + } |
| 55 | +} |
| 56 | +
|
| 57 | +print("An info") |
| 58 | +print("A warning", ~logLevel=#warn) |
| 59 | +``` |
| 60 | + |
| 61 | +```js |
| 62 | +function print(text, logLevelOpt) { |
| 63 | + var logLevel = logLevelOpt !== undefined ? logLevelOpt : "info"; |
| 64 | + if (logLevel === "warn") { |
| 65 | + console.warn(text); |
| 66 | + } else if (logLevel === "error") { |
| 67 | + console.error(text); |
| 68 | + } else { |
| 69 | + console.log(text); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +print("An info", undefined); |
| 74 | + |
| 75 | +print("A warning", "warn"); |
| 76 | +``` |
| 77 | + |
| 78 | +</CodeTab> |
| 79 | + |
| 80 | +### References |
| 81 | + |
| 82 | +* [Labeled Arguments](/docs/manual/latest/function#labeled-arguments) |
| 83 | +* [Optional Labeled Arguments](/docs/manual/latest/function#optional-labeled-arguments) |
| 84 | +* [Labeled Argument with Default Value](/docs/manual/latest/function#optional-with-default-value) |
| 85 | +* [Function Syntax Cheatsheet](/docs/manual/latest/function#tips--tricks) |
0 commit comments