0
0
Typescriptprogramming~15 mins

Default parameters with types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Default parameters with types
📖 Scenario: You are creating a simple greeting function for a website. Sometimes users provide their name, and sometimes they don't. You want to make sure the function works well in both cases.
🎯 Goal: Build a TypeScript function called greet that takes a name parameter with a default value and a type. The function should return a greeting message.
📋 What You'll Learn
Create a function named greet with a parameter name of type string
Set the default value of name to "Guest"
Return a greeting string using the name parameter
Call the function twice: once without arguments and once with the argument "Alice"
Print the results of both calls
💡 Why This Matters
🌍 Real World
Default parameters help make functions flexible and easier to use when some information is optional.
💼 Career
Understanding default parameters with types is important for writing clean, safe, and maintainable TypeScript code in real projects.
Progress0 / 4 steps
1
Create the greet function with a typed name parameter
Write a function called greet that takes one parameter named name of type string. Do not add a default value yet.
Typescript
Need a hint?

Use function greet(name: string) to define the function and return a greeting string using backticks.

2
Add a default value "Guest" to the name parameter
Modify the greet function so that the name parameter has a default value of "Guest".
Typescript
Need a hint?

Add = "Guest" after the parameter name: string to set the default.

3
Call greet twice: once without arguments and once with "Alice"
Write two lines: call greet() without arguments and store the result in greeting1, then call greet("Alice") and store the result in greeting2.
Typescript
Need a hint?

Use const greeting1 = greet() and const greeting2 = greet("Alice") to call the function.

4
Print the greetings stored in greeting1 and greeting2
Write two console.log statements to print greeting1 and greeting2.
Typescript
Need a hint?

Use console.log(greeting1) and console.log(greeting2) to show the greetings.