kenadet
kenadet

Reputation: 255

Angular 2: What does variable name with ? mean?

What does variable name with ? mark mean ? e.g.

Label?: string

I see this in lots of places and couldn't understand what it means.

Upvotes: 2

Views: 2564

Answers (1)

haku
haku

Reputation: 4505

? indicates the parameter is optional. This is something specific to typescript - not angular or javascript (in javascript, all parameters are optional by default).

From Typescript documentation,

In JavaScript, every parameter is optional, and users may leave them off as they see fit. When they do, their value is undefined. We can get this functionality in TypeScript by adding a ? to the end of parameters we want to be optional.

 function buildName(firstName: string, lastName?: string) {
     if (lastName)
         return firstName + " " + lastName;
     else
         return firstName; }

let result1 = buildName("Bob");                  // works correctly now 
let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters 
let result3 = buildName("Bob", "Adams"); // ah, just right

Upvotes: 4

Related Questions