1

Given there are two ways to write the code, which way is better in terms of effective code?

const { match: { params: { clientId = '' } } } = this.props;

const clientId = this.props?.match?.params?.clientId ?? ''

N.B. We can ignore the fact that any of the intermediary could be null. My question is more specific in terms of why everyone goes for object destructuring as default, when it could be written simply as in second format

wentjun
  • 40,384
  • 10
  • 95
  • 107
Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73

2 Answers2

3

You might want to use both techniques if there could be a null in the middle of the chain. Since you cannot have a default value for a null.

const {
  clientId = '',
  clientName = ''
} = this.props?.match?.params || {};
Dzhax
  • 31
  • 1
2

Sure, it will be the same, as they both maintain the reference, but imagine if you want to extract multiple keys from your props?

// first, do some kind of null check to make sure 
// that props?.match?.params is defined, as you can destructure 
// an undefined object.
const { match: { params: { clientId = '', clientName = '' } } } = this.props;

vs 

const clientId = this.props?.match?.params?.clientId ?? ''
const clientName = this.props?.match?.params?.clientName ?? ''

The first method (object destructuring) will be more concise.

But of course, if you are have eslint (with airbnb config) setup on your project, the prefer-destructuring rule will be enabled by default, and you will be flagged to use destructuring assignment.

wentjun
  • 40,384
  • 10
  • 95
  • 107