0

I have been tasked with re-writing some code for a client reservation form and I was hoping someone could explain the following syntax. I know its basically like an if statement but the way it is set up is a little obscure to me since I am somewhat new to JavaScript:

testDate.setHours
(
    ampm.value=="AM"?
    (timestr[0]==12?0:timestr[0]=timestr[0]):
    (timestr[0]==12?12:timestr[0]=timestr[0]+12)
);

The whole reasoning behind this problem that I am working on is to take a value in for the reservation time. It parses the string into an array where timestr[0] is the hour value. Based on AM/PM and the value the user inputs, it will do its conversion to set the hours to military time. I am not sure that this is even working correctly.

If someone could analyze this code, explain the syntax to me (?,:, etc.) and tell me if this is the appropriate way to convert the hours I would greatly appreciate it.

Thank you!

Dave

EDIT :

Also, would this be an identical way of writing it, just easier to understand:

if(ampm.value=="AM")
{
    if(timestr[0]==12)
    {
        timestr[0] = 0;
        testDate.setHours(timestr[0]);
    }
    else
    {
        testDate.setHours(timestr[0]);
    }
}
else
{
    if(timestr[0]==12)
    {
        testDate.setHours(timestr[0]);
    }
    else
    {
        timestr[0] = timestr[0] + 12;
        testDate.setHours(timestr[0]);
    }
}
MotoDave452
  • 388
  • 1
  • 4
  • 21
  • 1
    Look up ternary operators – Gary Nov 07 '14 at 13:55
  • this is not a peculiar javascript syntax, anyway. – Luca Rainone Nov 07 '14 at 13:58
  • possible duplicate of [Question mark in JavaScript](http://stackoverflow.com/questions/1771786/question-mark-in-javascript) – Qantas 94 Heavy Nov 07 '14 at 14:15
  • While I was wondering the syntax, and this may be present in the post you included, I was also asking if the time conversion looks to be set up correctly. Thank you for the other post though as this may provide extra insight into my syntax question. – MotoDave452 Nov 07 '14 at 14:22

2 Answers2

1

That's called a ternary operator.

var answer = boolean ? response_1 : response 2;

is the same as writing:

if (boolean) {
    answer = response_1;
} else {
    answer = response_2;
}

In your case part of that, timestr[0]==12?0:timestr[0]=timestr[0] means, if timestr[0] is 12, then 0, else timestr[0]=timestr[0]. That last bit, timestr[0]=timestr[0] is a weird way of just saying timestr[0]. It's likely an error.

Wrapping ternarys in more ternarys is often frowned upon as it's confusing.

Rich Bradshaw
  • 67,265
  • 44
  • 170
  • 236
1

It's called a ternary if and you really shouldn't use it like this - the code becomes very difficult to read. I would refactor it to use regular if statements, the developers who come after you will thank you!

The syntax works like this:

var result = boolean_value ? true_result : false_result;
codebox
  • 18,210
  • 7
  • 54
  • 77