⊗jstsPmFnOP 49 of 55 menu

Optional Function Parameters in TypeScript

You can make a function accept a variable number of parameters by declaring some (or all) of the parameters as optional.

To indicate that a parameter is optional, place a question mark after its name.

Let's declare the last name as an optional parameter in our function:

function func(first: string, last?: string) { return first + ' ' + last; }

If an optional parameter is not specified when the function is called, it will take the value undefined. Let's modify our function to take this into account:

function func(first: string, last?: string) { if (last !== undefined) { return first + ' ' + last; } else { return first; } }

You can simplify it by using a short form of verification:

function func(first: string, last?: string) { if (last) { return first + ' ' + last; } else { return first; } }

Let's now use our function. Let's call it with two parameters:

func('john', 'smit'); // will return 'john smit'

Let's call it with one parameter:

func('john'); // will return 'john'

Make a function that takes a day, month, and year as parameters and returns the day of the week corresponding to that date. Let all three parameters be optional. If any parameter is not passed, it should take the value corresponding to the current date.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline