Hidden power of || and &&
Tags: javascript, typescript, beginners
Published: 2021-05-24 08:36:52

---
title: Hidden power of || and &&
published: true
description: Let's learn few tricks with logical operators 👻
tags: javascript, typescript, beginners
cover_image: https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/1024px-Unofficial_JavaScript_logo_2.svg.png
---

TLDR: Logical operators actually return one of the operands, so you can refactor code using this feature.

---

Usually, you may see `||` and `&&` logical operators in if cases.

```javascript
if (case1 || case2) { 
  doSomething()
}
```

So you may expect that `||` and `&&` returns a boolean value, but it is only correct if values on both sides of these operators are boolean as well. 

Actually, these operators return one of their arguments. E.g. if they were functions they would be implemented like this.

```javascript
function or(a, b) {
  if (a) {
    return a
  }
  return b
}

function and(a, b) {
  if (a) {
    return b
  }
  return a
}
```

It may sound and look a bit confusing, but let’s dive into examples.

```javascript
let obj = { prop: 1 }

// boring part
true || false // -> true
false || true // -> true
true && false // -> false
false && true // -> false

// interesting part
obj || false // -> { prop: 1 }
false || obj  // -> { prop: 1 }

// more interesting part
true && obj // -> { prop: 1 }
obj && true // -> true 
true || obj  // -> true
obj || true // -> { prop: 1 }
```

Ok, how do we use it? 

Using the `||` operator you can set default values.

```javascript
const title = props.customTitle || 'Default title'

// Same to

let title = 'Default title'
if (props.customTitle) {
  title = props.customTitle
}
```

Using the `&&` operator we can check for property presence in an object.

```javascript
let name = response && response.data && response.data.name

// Same to

let name;
if (response) {
  if (response.data) {
    if (response.data.name) {
      name = response.data.name
    }
  }
}
```

So if `response` or `response.data` is `undefined` or `null` this assignment won’t throw any error.

Combining `||` and `&&` we can get a nice construction, which checks for properties and can set a default value.

```javascript
let name = response && response.data && response.data.name || 'UNKNOWN'
```

Btw in newer versions of TypeScript, you can use a nullish coalescing, which simplifies `&&` chains even more.

```typescript
let name = response?.data?.name || 'UNKOWN'
```

UPD: Needed to mention this can be confused with [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation#:~:text=In%20programming%20language%20theory%2C%20lazy,avoids%20repeated%20evaluations%20(sharing).), but actually it is [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation). Thanks to my friend [Ray](https://twitter.com/rayman1104)

UPD2: as @lukeshiru mentioned in the comments, it is better to use nullish coalescing instead of `&&` and `||`. 

It's because values like 0 are treated like falsy, which can introduce bugs.

```javascript
let beginnerCarDriver = {
  // ...
  yearsOfExperience: 0
}
let getDriveExperience = (driver) => 
  driver && driver.yearsOfExperience || "Not a driver"
console.log(getDriveExperience(beginnerCarDriver)) // Not a driver

let getDriveExperience1 = (driver) =>
  driver?.yearsOfExperience ?? "Not a driver"
console.log(getDriveExperience1(beginnerCarDriver)) // 0
```

**References**
[MDN/||](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)
[MDN/&&](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND)

**Previous posts**
* [JS interview in 2 minutes / pure vs impure functions](https://dev.to/kozlovzxc/js-interview-in-2-minutes-pure-vs-impure-functions-22om)
* [JS interview in 2 minutes / Closure](https://dev.to/kozlovzxc/js-interview-in-2-minutes-closure-3hi6)
* [JS interview in 2 minutes / Currying 🥘](https://dev.to/kozlovzxc/js-interview-in-2-minutes-currying-2hko)

---

Btw, I will post more fun stuff here and on [Twitter](https://twitter.com/kozlovzxc). Let's be friends 👋