Reputation: 379
Sorry to bring this up with what some might consider easy syntax but I am having trouble wrapping my head around this.One => this.IsWeird
So I have some code:
get items(): readonly TodoItem[] {
return this.list.items.filter(item => this.showComplete || !item.complete);
}
showComplete: boolean = false;
Apparently this is the equivalent of :
get items(): readonly TodoItem[] {
if (this.showComplete == true) {
return this.list.items;
}
if (this.showComplete == false) {
return this.list.items.filter(item => !item.complete);
}
}
showComplete: boolean = false;
The '||' operator in the lambda function is what throws me off. What operator would I use if I wanted the reverse to happen, say if I wanted to return the items that are not complete if showComplete was true? Thanks for looking, sorry if this should be apparent to me.
Upvotes: 0
Views: 756
Reputation: 439
The logical OR operator a || b
can be used as a shorthand in JavaScript for if a is not true, evaluate b
. It works due to short-circuit evaluation, which means that if a
is true, it does not need to evaluate the rest of the expression as it is irrelevant, the expression will be true anyway. However, if a
is false, it will execute b
to fully evaluate the expression.
In the .filter()
method, if this.showComplete
is true, it will return true for every entry (i.e. it will only evaluate this.showComplete
). If this.showComplete
is false, it will evaluate the whole expression and return !item.complete
.
To change the response to do the opposite as you ask, you could change it to:
return this.list.items.filter(item => this.showComplete && !item.complete);
a && b
is also a shorthand expression in JavaScript for if a is true, evaluate b
. So in this case, when this.showComplete
is true, the second part of the expression will also be evaluated. When this.showComplete
is false, nothing will be returned as every evaluation will return false.
Upvotes: 1