undefined passes if?

  • 1
  • Problem
  • Updated 3 years ago
  • Solved
Here's part of some code for a custom table view:

.attr('href', '/support/servlet/servlet.FileDownload?file=' + 		             (row.Support_User__r && row.Support_User__r.Photo__r) ? 
       row.Support_User__r.Photo__r.skuid__AttachmentId__c : 
       null
)

I'm getting a javascript error on row.Support_User__r.Photo__r.skuid__AttachmentID__c:
Uncaught TypeError: Cannot read property 'skuid__AttachmentId__c' of undefined

How could the code get past the IF ? when Photo__r is undefined?

Any idea what might be going on here?
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb

Posted 3 years ago

  • 1
Photo of Thimo

Thimo

  • 1,280 Points 1k badge 2x thumb
That's because of precedence of the operators.

? is considered more important than +

Your statement 

'/support/servlet/servlet.FileDownload?file=' + 		             (row.Support_User__r && row.Support_User__r.Photo__r)  ?  row.Support_User__r.Photo__r.skuid__AttachmentId__c :  null

is interpreted as

('/support/servlet/servlet.FileDownload?file=' + (row.Support_User__r && row.Support_User__r.Photo__r))  ?  (row.Support_User__r.Photo__r.skuid__AttachmentId__c) : (null)

 try putting the whole inline-if into brackets like

 '/support/servlet/servlet.FileDownload?file=' + ((row.Support_User__r && row.Support_User__r.Photo__r)  ?  row.Support_User__r.Photo__r.skuid__AttachmentId__c :  null)
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Thanks, Thimo!