---
title: "Use OR instead of Ternary Operator"
url: "https://blog.beyondthecloud.dev/tips/use-or-instead-of-ternary-operator"
category: "LWC"
published: "2024-03-06"
---

# Use OR instead of Ternary Operator

You probably used the logical JS operator OR (||) in your Lightning Web Components. The most common use cases involve conditional statements.

### 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.

```javascript
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.

```javascript
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...

```javascript
get language() {
    if (user.language) {
        return user.language;
    }

    return 'en-US';
}
```

```javascript
get language() {
    return user.language ? user.language : 'en-US';
}
```

```javascript
get language() {
    return user.language || 'en-US';
}
```

```javascript
handleChange(event) {
    this.tabset = event?.target?.dataset?.tabset || DEFAULT_TABSET;
}
```

```javascript
this.showToast({
    title: 'Unexpected error',
    message: error?.message || error?.body?.message || labels.contactAdministrator,
    variant: 'error'
});
```
