0

I want to find a way to combine multiple if statements all to one line with some clever spacing.

var myBool = myObject.prop1 ||
    myObject.prop2 && 
    myObject.prop3.someproperty

Since prop3 might be empty so I want to check if "someproperty" exist in prop3. But I do not want to add another if statement like typeof myObject.prop3.someproperty === 'undefined before my myBool.

Is there anyway that I can make everything in one line with clever spacing?

CherylG
  • 1,032
  • 8
  • 23
  • So do you mean `prop3` might be `undefined` or `prop3.someproperty` might be undefined. If the later, then your code as it is should be fine. `undefined` is falsy so that condition will evaluate as false anyway. – Matt Burland Mar 14 '16 at 21:02
  • `.prop2 && (myObject.prop3 && myObject.prop3.someproperty)` – adeneo Mar 14 '16 at 21:06
  • 1
    take in mind, that && comes before || so, so in your statement if prop1 is true the statement is true. – Jarlik Stepsto Mar 14 '16 at 21:07
  • @JarlikStepsto Yes, that is what I want. – CherylG Mar 14 '16 at 21:13
  • Related question: [How to use the ?: ternary operator in JavaScript](http://stackoverflow.com/questions/6259982/how-to-use-the-ternary-operator-in-javascript) – Yogi Mar 14 '16 at 21:31

2 Answers2

0
var myBool = myObject.prop1 ||
    myObject.prop2 && 
    myObject.prop3.someproperty != null
    ? myObject.prop3.someproperty
    : false
Alex
  • 21,273
  • 10
  • 61
  • 73
dodo
  • 156
  • 10
0
var myBool = Boolean(myObject.prop1 ||
    myObject.prop2 && 
    myObject.prop3 && myObject.prop3.someproperty);

or

var myBool = !!(myObject.prop1 ||
    myObject.prop2 && 
    myObject.prop3 && myObject.prop3.someproperty);

since your naming implies that you expect myBool to contain a real boolean, not some truthy or falsy value

Thomas
  • 3,513
  • 1
  • 13
  • 10