- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 232字
- 2021-07-15 17:05:33
Optional and default parameters
Say, for example, we have a function with three parameters, and sometimes we may only pass values for the first two parameters in the function. In TypeScript, we can handle such scenarios using the optional parameter. We can define the first two parameters as normal and the third parameter as optional, as given in the following code snippet:
function CustomerName(firstName: string, lastName: string, middleName?: string) { if (middleName) return firstName + " " + middleName + " " + lastName; else return firstName + " " + lastName; } //ignored optional parameter middleName var customer1 = customerName("Rajesh", "Gunasundaram"); //error, supplied too many parameters var customer2 = customerName("Scott", "Tiger", "Lion", "King"); //supplied values for all var customer3 = customerName("Scott", "Tiger", "Lion");
Here, middleName is the optional parameter, and it can be ignored when calling the function.
Now, let's see how to set default parameters in a function. If a value is not supplied to a parameter in the function, we can define it to take the default value that is configured:
function CustomerName(firstName: string, lastName: string, middleName:
string = 'No Middle Name') { if (middleName) return firstName + " " + middleName + " " + lastName; else return firstName + " " + lastName; }
Here, middleName is the default parameter that will have No Middle Name by default if the value is not supplied by the caller.
推薦閱讀
- Learn ECMAScript(Second Edition)
- Cocos2d-x游戲開發:手把手教你Lua語言的編程方法
- PyQt從入門到精通
- Learning Elixir
- DevOps入門與實踐
- Julia數據科學應用
- Learning Concurrency in Python
- Mastering Drupal 8
- 體驗之道:從需求到實踐的用戶體驗實戰
- Python深度學習(第2版)
- Android熱門應用開發詳解
- R語言與網站分析
- Implementing DevOps with Ansible 2
- Practical XMPP
- Mastering Wireless Penetration Testing for Highly Secured Environments