Ternary operation order


Does ternary operation order matter? My function accepts two arguments. The first is always a number, and the second can be anything. I’m using the ternary operation to check if the 2nd argument is a number, then add to the first number. It works if the ternary comes first, but fails otherwise.

function addTogether() {
  var result;  
  var num1 = arguments[0];
  // case #1, this one fails
  result = num1 + typeof arguments[1] != "number" ? undefined: arguments[1] ;
  // case #2, this one works
//   result = typeof arguments[1] != "number" ? undefined: arguments[1] + num1;
  return result;

// addTogether2(2, 3); // expecting 5, produce by case #2 only
addTogether2(2, "3"); // expecting undefined, produce by both cases


I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


If you wrap the ternary in some parentheses it’ll work just fine:

result = num1 + (typeof arguments[1] != "number" ? undefined: arguments[1]);

However, adding undefined to a number doesn’t return undefined, it returns NaN.

  • With ternary operations, the first section, before ?, requires an expression of Boolean (true or false.)
  • Sections two and three depends on the desired result of the Boolean expression.
  • Also, review JS conversions between numbers and strings.
  1. Your function does not accept any parameters.
  2. You should re-examine the Boolean expressions…

I would first start with reviewing these resources.
Conditional (Ternary) Operator (JavaScript)