Use OR instead of Ternary Operator
Use OR (||) instead of IFs and Ternary Operators
You probably used the logical JS operator OR (||) in your Lightning Web Components. The most common use cases involve conditional statements.
You probably used the logical JS operator OR (||) in your Lightning Web Components. The most common use cases involve conditional statements.
const a = 3;
const b = -2;
if (a > 0 || b > 0) {
// ...
}But did you know that || is a great operator to replace IF and Ternary Operator statements?
As we can read in the documentation:
[OR] It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non- Boolean values, it will return a non-Boolean value.
import { LightningElement, api } from 'lwc';
export default class MyComponentName extends LightningElement {
@api error;
get errorMessage() {
return this.error || 'Unexpected Error. Please contact your administrator!'
}
}OR (||) operator will return the first value that is NOT null, NaN, 0, empty (‘’), or undefined.
Check out more examples...
get language() {
if (user.language) {
return user.language;
}
return 'en-US';
}get language() {
return user.language ? user.language : 'en-US';
}get language() {
return user.language || 'en-US';
}handleChange(event) {
this.tabset = event?.target?.dataset?.tabset || DEFAULT_TABSET;
}this.showToast({
title: 'Unexpected error',
message: error?.message || error?.body?.message || labels.contactAdministrator,
variant: 'error'
});

