awscr
awscr

Reputation: 3

Ternary operator returns 'undefined' instead of expected value

Given a number, the function must return the negative of that number (it might already be negative). Why does the ternary operator not work in this case? Using an if statement works.

// Does not work
function makeNegative(num) {
  num < 0 ? num : -num;
}

// Works
function makeNegative(num) {
  if (num < 0) {
    return num;
  }
  return -num;
}

// TEST
console.log(makeNegative(-4)); //-4
console.log(makeNegative(6)); //-6

Upvotes: 0

Views: 380

Answers (3)

Robo Robok
Robo Robok

Reputation: 22663

You still need to return your value:

function makeNegative(num) {
    return num < 0 ? num : -num;
}

If you want to use implicit returns, you need to convert your function to an arrow function:

const makeNegative = num => num < 0 ? num : -num;

By the way, you can use negative Math.abs() for that purpose:

const alwaysNegative = -Math.abs(num);

Upvotes: 3

Diego Plata
Diego Plata

Reputation: 51

You are missing the return statement in the ternary operator function. Try it like this:

function makeNegative(num) {
  return(num < 0 ? num : -num);
}

Upvotes: 1

applemonkey496
applemonkey496

Reputation: 743

You need to assign num, you are missing the =:

function makeNegative(num) {
  num = (num < 0) ? num : -num;
}

For more information, you can check out the docs.

EDIT: I looked at the question again, and given the usage in this case, this will not work. If you were looking to apply the method to the number without a return value, this would be the solution, but in this case, you would be looking for a return statement. I will keep my answer here as reference for others, but it is not the answer to @Awscr's question.

Upvotes: -1

Related Questions