-2

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;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
tygar
  • 244
  • 1
  • 4
  • 15
  • 1
    have you tried it? what happened? – Nina Scholz Jun 12 '17 at 06:00
  • Per [*ECMA-262*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-conditional-operator), The bits either side of the `:` need to be [*assignment expressions*](http://www.ecma-international.org/ecma-262/7.0/index.html#prod-AssignmentExpression), they can't contain [*statements or declarations*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-ecmascript-language-statements-and-declarations) like a [*for* statement](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-for-statement). – RobG Jun 12 '17 at 06:10
  • provide more context, if n is an array we can give you a better answer. You can use every and some in place of a for loop in a conditional – Rick Jun 12 '17 at 06:17

3 Answers3

0

You can use only expressions inside of a conditional (ternary) operator ?:. A for statement is not an expression.

But you could use a ternary statement, without for loop and the Gausss formular for getting the result for even numbers.

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

console.log(f(4));
console.log(f(5));

An even shorter version could utilize the logical AND &&

function f(n) {
    return n % 2 === 0 && n > 0 && n * (n + 1) / 2;
}

console.log(f(4));
console.log(f(5));

The other possibillity is to wrap the whole for statement in an IIFE.

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

console.log(f(4));
console.log(f(5));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You cano't use for inside a ternary if,
Insted you can use a function to do the for to you :

function calc(num){
  var p = 0;
   for(let i = 1; i <= num; i++) {
     p += i;
   }
   
   return p;
}

function f(n){
  var p = 0;
  p = ((n % 2 === 0) && (n > 0)) ? calc(n) : 
  false;
  return p;
}

console.log(f(4));
console.log(f(5));
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
0

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));
pid
  • 11,472
  • 6
  • 34
  • 63