I want to write this code using ternary operator
That's not a ternary operator (an operator accepting three operands), it's the &&
, which is a binary operator (an operator accepting two operands). The only ternary operator in JavaScript right now is the conditional operator (condition ? valueIfTruthy : valueIfFalsy
).
The problem is that when you combine things with &&
, the right-hand operand is only evaluated if the left-hand operand's value is truthy. I guess getName
is returning something falsy, which is why the right-hand operand isn't evaluated (getLastName
isn't called). &&
short-circuits.
Don't rewrite the if
. It's perfectly clear and straightforward and easy to debug the way it is. It's not broken.
If you were going to use &&
instead of if
, you'd use the comma operator (a binary operator) for the two operations:
// Please don't do this
a === 10 && (getName(), getLastName());
The comma operator evaluates its left-hand operand, throws the result away, and then evaluates its right-hand operand and takes that result as its result.
But again: Please don't. :-)