MotoDave452
MotoDave452

Reputation: 406

Understanding JavaScript Syntax

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]);
    }
}

Upvotes: -1

Views: 72

Answers (2)

codebox
codebox

Reputation: 20264

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;

Upvotes: 1

Rich Bradshaw
Rich Bradshaw

Reputation: 73055

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.

Upvotes: 1

Related Questions