is this can be done by Short-circuit technique like this ? it will check for null first then .
if ( $box  && $box instanceof Array && $box.length > 0 && 'contains' in $box[0] && !$box[0].contains(e.target) && e.target !== $overlay[0]  )