35
loading...
This website collects cookies to deliver better user experience
?
symbol (question mark) after the parameter name when defining function in TypeScript.// a simple function that returns
// a greeting with an optional name parameter
function sayGreeting(name?: string) {
return name ? `Hey ${name}` : `Hey Person`;
}
// call the function
sayGreeting("John Doe"); // Hey John Doe
// call the function
// but with no value
sayGreeting(); // ✅ Ok. Hey Person
sayGreeting
which has a parameter called name
and returns a greeting with the name
value.// a simple function that returns
// a greeting with the name
function sayGreeting(name: string) {
return `Hey ${name}`;
}
John Doe
as an argument, it will return the string Hey John Doe
which is the correct behavior.// a simple function that returns
// a greeting with the name
function sayGreeting(name: string) {
return `Hey ${name}`;
}
// call the function
sayGreeting("John Doe"); // Hey John Doe
sayGreeting
function and pass no value as an argument to the function like this,// a simple function that returns
// a greeting with the name
function sayGreeting(name: string) {
return `Hey ${name}`;
}
// call the function
sayGreeting("John Doe"); // Hey John Doe
// call the function
// but with no value
sayGreeting(); // ❌ Error. Expected 1 arguments, but got 0.
Expected 1 arguments, but got 0.
. In simple terms, it means that we need to pass at least one value as an argument to the function.name
parameter as an optional argument we can use the question mark symbol (?
) before the parameter name like this,// a simple function that returns
// a greeting with an optional name parameter
function sayGreeting(name?: string) {
return `Hey ${name}`;
}
// call the function
sayGreeting("John Doe"); // Hey John Doe
// call the function
// but with no value
sayGreeting(); // ✅ Ok.
undefined
value if no value is passed to the name
parameter we can add a ternary operator
check to see if the name
parameter is empty and return the result according to it.// a simple function that returns
// a greeting with an optional name parameter
function sayGreeting(name?: string) {
return name ? `Hey ${name}` : `Hey Person`;
}
// call the function
sayGreeting("John Doe"); // Hey John Doe
// call the function
// but with no value
sayGreeting(); // ✅ Ok. Hey Person