- 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.
- FuelPHP Application Development Blueprints
- Learn TypeScript 3 by Building Web Applications
- Spring 5企業(yè)級開發(fā)實(shí)戰(zhàn)
- Visual FoxPro程序設(shè)計(jì)教程(第3版)
- 構(gòu)建移動(dòng)網(wǎng)站與APP:HTML 5移動(dòng)開發(fā)入門與實(shí)戰(zhàn)(跨平臺(tái)移動(dòng)開發(fā)叢書)
- JavaScript 網(wǎng)頁編程從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Rust編程從入門到實(shí)戰(zhàn)
- Apache Spark 2 for Beginners
- C語言程序設(shè)計(jì)
- Java面向?qū)ο蟪绦蜷_發(fā)及實(shí)戰(zhàn)
- Python應(yīng)用輕松入門
- Java EE 7 Development with NetBeans 8
- Linux命令行與shell腳本編程大全(第4版)
- 編程數(shù)學(xué)
- Bootstrap 4 Cookbook