Search code examples
javascriptconditional-statementsternary

Can we run for loops inside a conditional operator (? :)?


i have this code:

function f(n){
var p = 0;
if(n % 2 === 0 && n > 0) {
  for(let i = 1; i <= n; i++) {
    p += i;
  };
} else {
    return false;
    }
 return p;
};

And was wondering if it was possible to convert to ternary operator to shorted it. This is the code i have come up with but its obviously incorrect, any insight would be good! Cheers.

function f(n){
  var p = 0;
  ((n % 2 === 0) && (n > 0)) ? for(let i = 1; i <= n; i++) {p += i;} : 
  false;
  return p;
}

Solution

  • If I were you I'd use Gauss and write it this way:

    function f(n)
    {
      return n > 0 && n % 2 === 0 ? n * (n + 1) / 2 : false;
    }
    
    console.log(f(4));
    console.log(f(5));