Need help understanding what is going into this array..

trans[“amountDisplay”] = (type ==="withdrawal) ? “(” + amount + “)” : amount;

Code is from an Account Balance Calculator and I understand the other components added to the array trans but this one is busting my chops.

Thank you.

There are a couple of things going on here. First, if trans is an array, what’s being “added” to it is not an array element. Instead, a property on the array object named “amountDisplay” is being set. This is equivalent to using trans.amountDisplay = ....

Then the assignment is using the ternary operator. This is like a condensed if-else which returns one of two values depending on a condition

Here, the condition is (type ==="withdrawal"). If that resolves to true, the value following the question mark (?) is returned, or "(" + amount + ")". If it resolves to false, the value following the colon (:) is returned, or simply amount.

So basically, what you have here is the amountDisplay property of the trans object being set to either the value of amount, or the value of amount inside parens depending on whether or not type has a value of “withdrawal” or not.

1 Like

Thank you. I thought it had to be some sort of if/else relationship but I was unfamiliar with the syntax.