Reputation: 604
Which is better way for handling optional input parameters?
@Input() public isActive?: boolean;
or
@Input() public isActive: boolean = undefined;
And also a little puzzle, what would be a result of below code and why (if in the view isActive
is not specified)?
@Input() public isActive?: boolean = undefined;
with
<app-sth [otherParameter]="true"></app-sth>
Upvotes: 1
Views: 392
Reputation: 3491
Which is better way for handling optional input parameters?
There is no difference between the 2 statements: @Input() public isActive?: boolean
and @Input() public isActive: boolean = undefined
.
Both are undefined.
Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#Description:
A variable that has not been assigned a value is of type undefined.
The first statement hasn't been assigned a value, so it is undefined. The second statement has been assigned an undefined type, hence, it is undefined.
On a side note, even if you assign a value of null
to the property, e.g. @Input() public isActive: boolean = null;
, the JS engine will not evaluate the property to be false. Because null is neither true nor false.
If you are curious on what is the difference between null and undefined, you may have a read here: What is the difference between null and undefined in JavaScript?
And also a little puzzle, what would be a result of below code and why (if in the view isActive is not specified)?
Nothing, no error would be thrown because you have declared the property to "optional", you may know it as "nullable" if you are coming from other languages.
Upvotes: 2