export class SearchResult {
id: string;
constructor(obj?: any) {
this.id = obj && obj.id || null;
}
}
What does obj && obj.id || null mean? I don't get this syntax.
export class SearchResult {
id: string;
constructor(obj?: any) {
this.id = obj && obj.id || null;
}
}
What does obj && obj.id || null mean? I don't get this syntax.
Whilst your code is using Typescript, this question actually concerns JavaScript.
In JavaScript:
true && expression
will cause the expression to be evalauted.
As for:
false && expression
this will evaluate to false causing the expression to not be evaulated.
Hence in your constructor, if obj is truthy (e.g. neither null or undefined) the expression will be evaluated, in this case accessing the obj.id and assigning its value to this.id. If obj is not truthy, then it will evaluate to false, and the null value will get assigned to this.id.
This technique is often used in React, see here for an example.
true && expression evaluated to true. I guess because usually when I use this concept, I'm trying to use the value as truthy and it works