Mikel Wohlschlegel
Mikel Wohlschlegel

Reputation: 1476

Check existance of element and assign to variable in one line

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

Answers (2)

Akxe
Akxe

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

BadHorsie
BadHorsie

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

Related Questions