Bangsi Bangsi - 18 days ago 6
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
undefined(…)


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

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.

Comments