12

Curious to know if there's any part of ES6 that makes these kind of checks a little more concise:

componentWillReceiveProps(nextProps) {
    if(nextProps && nextProps.filterObj && nextProps.filterObj.area){
        // go ahead
    }
}
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • Do you want to read it or modify? For reading you may destructure it. – zerkms May 22 '15 at 11:18
  • Short answer is no. I don't understand how destructuring will help. `var { filterObj: { area } } = nextProps;` will return the same error that `nextProps.filterObj.area` would. –  May 22 '15 at 11:55

1 Answers1

12

No, no existential operator has made it into ES6; it is still discussed however.

You can use any of the existing methods, of course, like

if ( ((nextProps||{}).filterObj||{}).area ) {
    // go ahead
}

Also you can try destructuring and default values:

function componentWillReceiveProps({filterObj: {area} = {}} = {}) {
    if (area) {
        // go ahead
    }
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The problem with this approach is that it will swallow zeroes, empty strings and arrays. The correct way is to compare against `undefined` but it makes the code way too bulky. – Andrey Mikhaylov - lolmaus Jul 27 '15 at 12:02
  • @lolmaus-AndreyMikhaylov: I don't see why it would swallow zeroes and empty strings, you surely don't expect these anyway when you want to access another property on the value? If you mean for the `.area`, you surely can append a `!== undefined` comparison. And no, it certainly won't swallow arrays. – Bergi Jul 27 '15 at 12:40
  • For example, you want `3` to be a default value, but `0` is also a legit value. If you do `value||3`, it will be impossible to pass a zero. – Andrey Mikhaylov - lolmaus Jul 27 '15 at 12:51
  • @lolmaus-AndreyMikhaylov: the only default value you use here is `{}` - when accessing properties, we only consider objects to be legit values. – Bergi Jul 27 '15 at 13:01