2

My project is littered with things like :

if(selectedDestination.modeOfTransport && selectedDestination.modeOfTransport.value === 'Driving'"){ 
  // Do something
}

Ideally I'd like to just have:

if(selectedDestination.modeOfTransport.value === 'Driving'")

and let it just be false if there's no 'modeOfTransport' property.

abyrne85
  • 1,370
  • 16
  • 33

1 Answers1

3

something like that should suit:

(selectedDestination.modeOfTransport || {}).value === 'Driving'

// or (to avoid prototype inheritance) 
(selectedDestination.modeOfTransport || Object.create(null)).value === 'Driving'

If you're using babel, you can have a look at: Nullish Coalescing for JavaScript

selectedDestination.modeOfTransport?.value === 'Driving'

Tim's edit: Here is another option:

This is a common problem in JavaScript. One cop out answer might be to define a variable which referenced the lengthy expression you want to avoid:

var mode = selectedDestination.modeOfTransport;
if (mode && mode.value === 'Driving') { 
    // Do something
}
Hitmands
  • 13,491
  • 4
  • 34
  • 69
  • While this would work, this is not the solution the OP requested. He wants to remove the `AND` gate as well as `XOR` most likely to keep his logical statements 'clean'. – Adrian Dec 07 '17 at 11:17
  • If object is empty how will it have a 'value' key? – Mandeep Jain Dec 07 '17 at 11:17
  • @MandeepJain it won't but you won't throw exception either looking for a property of object that doesn't exist – charlietfl Dec 07 '17 at 11:18
  • @MandeepJain It will just return `undefined`. If you tried to obtain another property from `.value` e.g. `.value.anothervalue` then it would throw. – Adrian Dec 07 '17 at 11:19
  • 1
    @MandeepJain - that's the point :) - if selectedDestination.modeOfTransport is undefined then use `{}.value` - which is undefined, doesn't equal 'Driving' and doesn't result in an uncaught TypeError – Danield Dec 07 '17 at 11:20
  • ohh. got it. Thanks. Its dirty but effective – Mandeep Jain Dec 07 '17 at 11:21
  • 1
    @MandeepJain `dirty` ? – Hitmands Dec 07 '17 at 11:24
  • I like the babel solution. But is there any gotchas that are worth knowing? I've already spotted one. It works fine in the html template, but typescript complains if its in the ts file – abyrne85 Dec 07 '17 at 11:30
  • 1
    @abyrne85 [Suggestion: "safe navigation operator", i.e. `x?.y`](https://github.com/Microsoft/TypeScript/issues/16) – Hitmands Dec 07 '17 at 11:49