ajp76054
ajp76054

Reputation: 33

How to reduce this if statement check in JavaScript

How can I reduce this if statement in JavaScript

if(obj.attributes && obj.attributes.email === '[email protected]') { ... }

Upvotes: 1

Views: 301

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can create a reusable get function using Array.reduce(). The function parameters are a path, the object, and a defaultValue (default defaultValue is undefined). It will iterate the path, and try to extract the value, if it fails, it will return the defaultValue:

const get = (path, obj, defaultValue) => obj ? 
  path.reduce((r, k) => r && typeof r === 'object' ? r[k] : defaultValue, obj) 
  : 
  defaultValue;

if(get(['attributes', 'email'], null) === '[email protected]') { console.log(1) }
if(get(['attributes', 'email'], {}) === '[email protected]') { console.log(2) }
if(get(['attributes', 'email'], { attributes: {} }) === '[email protected]') { console.log(3) }
if(get(['attributes', 'email'], { attributes: { email: '[email protected]' } }) === '[email protected]') { console.log(4) }

There is a TC39 stage proposal called "Optional Chaining for JavaScript". If it will make it's way to the language, it will add an the optional chaining operator - ?. Now if attributes don't exist, it will return undefined.

Example: obj.attributes?.email

It's usable today via babel plugin.

Upvotes: 0

Crisoforo Gaspar
Crisoforo Gaspar

Reputation: 3830

The line by it self is clear, however if you are looking a way to write less && operator inside you can always put things outside of the comparison such as.

var attributes = obj.attributes || {};
if ( attributes.email === '[email protected]' ) {
}

This makes sense if you need to make multiple checks instead of a single one, however if is a single comparison it seems like the code you already have is okay as you are making sure attributes is defined before accessing an undefined property.

On the other hand if you have support for ES 2015 you can destruct stuff like:

const { attributes = {} } = obj;
if ( attributes.email === '[email protected]' ) {
}

Upvotes: 1

Related Questions