Bangsi Bangsi - 1 year ago 64
Javascript Question

JavaScript ternary if x && y else

$scope.input.opening_hours = place.opening_hours && place.opening_hours.weekday_text ? place.opening_hours.weekday_text : '';

Uncaught TypeError: Cannot read property 'weekday_text' of

if ( place.opening_hours && place.opening_hours.weekday_text ) {
$scope.input.opening_hours = place.opening_hours.weekday_text;
} else {
$scope.input.opening_hours = '';

I am trying to make a ternary version of this if statement but I get the error above. Whats the best way to simplify this to a simpler statement.

Answer Source

As I tell you in comments, you need to add parenthesis:

$scope.input.opening_hours = (place.opening_hours && place.opening_hours.weekday_text) ? place.opening_hours.weekday_text : '';

And you can improve:

$scope.input.opening_hours = ((place.opening_hours && place.opening_hours.weekday_text) ? place.opening_hours.weekday_text : '');

The latter ensures that inner parenthesis will be executed before all. It's like maths, the inner parenthesis needs to be executed before outer parenthesis.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download