- Hands-On Functional Programming with TypeScript
- Remo H. Jansen
- 350字
- 2021-07-02 14:03:13
Functions with default parameters
When a function has some optional parameters, we must check whether an argument has been passed to the function (just like we did in the previous example) to prevent potential errors.
There are a number of scenarios in which it would be more useful to provide a default value for a parameter when it is not supplied than to make it an optional parameter. Let's rewrite the add function (from the previous section) using the inline if structure:
function add(foo: number, bar: number, foobar?: number): number {
return foo + bar + (foobar !== undefined ? foobar : 0);
}
There is nothing wrong with the preceding function, but we can improve its readability by providing a default value for the foobar parameter instead of using an optional parameter:
function add(foo: number, bar: number, foobar: number = 0): number {
return foo + bar + foobar;
}
To indicate that a function parameter is optional, we need to provide a default value using the = operator when declaring the function's signature. After compiling the preceding examples, the TypeScript compiler will generate an if statement in the JavaScript output to set a default value for the foobar parameter if it is not passed as an argument to the function:
function add(foo, bar, foobar) {
if (foobar === void 0) { foobar = 0; }
return foo + bar + foobar;
}
This is great because the TypeScript compiler generated the code required to prevent potential runtime errors for us.
The void 0 parameter is used by the TypeScript compiler to check whether a variable is equal to undefined. While most developers use the undefined variable to perform this kind of check, most compilers use void 0 because it will always evaluate as undefined. Checking against undefined is less secure because its value could have been modified, as demonstrated by the following code snippet:
function test() {
var undefined = 2; // 2
console.log(undefined === 2); // true
}
Just like optional parameters, default parameters must always be located after any required parameters in the function's parameter list.
- Software Defined Networking with OpenFlow
- Object-Oriented JavaScript(Second Edition)
- Effective Python Penetration Testing
- ArcGIS By Example
- Android程序設計基礎
- QGIS Python Programming Cookbook(Second Edition)
- Node.js開發指南
- Raspberry Pi Robotic Blueprints
- Unity 2018 Augmented Reality Projects
- C編程技巧:117個問題解決方案示例
- Python預測分析實戰
- Software-Defined Networking with OpenFlow(Second Edition)
- Visual Basic程序設計基礎
- C語言程序設計
- Java核心技術速學版(第3版)