K48 K48 - 9 days ago 5
Javascript Question

JavaScript's inline If/Else with string concatenation returns unexpected value

I am using this JavaScript code to add an item into an array of objects containing search criteria.

My goal is to use "T00:00:00" if the search criterion is the beginning of the date range, and "T23:59:59" if it is the end of the date range.

//key = "Created",
//value = "2016-11-23",
//to_from = "from"
collectedValues.push({
key: key,
value: (value +
(to_from === "to") ?
"T23:59:59" : // when searching by date range,
"T00:00:00"), // "from" must be 00:00 and
// "to" must be 23:59
isPartialMatch: false,
toFrom: to_from
});


The resulting array of objects has the wrong value for the item's "value" property. It is supposed to be concatenated, like this: "2016-11-23T23:59:59".

Instead, it just has the value of "23:59:59".

enter image description here

It looks like this has something to do with code formatting and splitting into multiple lines.

Of course I could use the full if/else notation, but why doesn't this notation work?

Answer

Just change the order of the brackets. The inline IF condition doesn't need to be wrapped in brackets, like a normal if (something) syntax.

This code will work:

            collectedValues.push({
                key: key,
                value: value + (to_from === "to" ?
                        "T23:59:59" :   // when searching by date range,
                        "T00:00:00"),   // "from" must be 00:00 and 
                                        // "to" must be 23:59
                isPartialMatch: false,
                toFrom: to_from
            });
Comments