Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 24, 2021 08:36 am GMT

Hidden power of || and &&

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.

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.

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 lets dive into examples.

let obj = { prop: 1 }// boring parttrue || false // -> truefalse || true // -> truetrue && false // -> falsefalse && true // -> false// interesting partobj || false // -> { prop: 1 }false || obj  // -> { prop: 1 }// more interesting parttrue && obj // -> { prop: 1 }obj && true // -> true true || obj  // -> trueobj || true // -> { prop: 1 }

Ok, how do we use it?

Using the || operator you can set default values.

const title = props.customTitle || 'Default title'// Same tolet title = 'Default title'if (props.customTitle) {  title = props.customTitle}

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

let name = response && response.data && response.data.name// Same tolet 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 wont throw any error.

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

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.

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

UPD: Needed to mention this can be confused with lazy evaluation, but actually it is short-circuit evaluation. Thanks to my friend Ray

References
MDN/||
MDN/&&

Previous posts

Btw, I will post more fun stuff here and on Twitter. Let's be friends


Original Link: https://dev.to/kozlovzxc/hidden-power-of-and-jng

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To