Reputation: 1476
Can the following check and assignment be written with one line?
const panel = this.element.querySelector(".c-global-search__panel");
this.panel = (panel instanceof HTMLElement) ? panel : null;
Something like:
this.panel = (variable = querySelection and condition) ? assignment : fallback;
Upvotes: 0
Views: 622
Reputation: 11575
You can use simple ||
(or), as the return value of querySelector
is HTMLElement | null
. HTMLElement
is truth thus it will be returned, if it is null, fallback is used.
this.panel = this.element.querySelector(".c-global-search__panel") || fallback;
There is also null coalescing operator. This is new and not yet supported by browser (TS and Babel only), but it is better as it does treat false and 0 as valid value too. But in this case it is not needed.
this.panel = this.element.querySelector(".c-global-search__panel") ?? fallback;
But a side note... The engine will do this optimization anyway, there is no real need to do it. Rather than one-liners focus on readability.
Upvotes: 1
Reputation: 14564
You do not need the second line. querySelector() already returns null
if no element is found.
this.panel = this.element.querySelector(".c-global-search__panel");
Your second line setting the value to null
is redundant.
Upvotes: 1