0

I would like to replace if statement with the ternary operator. The case in my code is that I would like to use one if statement rather than if-else. But it seems ternary operators take a mandatory else statement.

My intended code that produces error is:

for(let i = 0; i<fibArr.length; i++) {
    !fibArr[i] % 2 === 0 ? result += fibArr[i]; //The problem area
}

Instead, I have to write the code that runs without any problems:

for(let i = 0; i<fibArr.length; i++) {
    if(fibArr[i] % 2 !== 0) {
        result += fibArr[i]
    }
}

Full code:

function sumFibs(num) {
    let a = 0, b = 1, fib = 0; 
    let i = 0; 
    let fibArr = []
    let result = 0; 

    while(fib <= num){
        fibArr.push(fib)
        a = b; 
        b = fib; 
        fib = a+b; 
    }

    for(let i = 0; i<fibArr.length; i++) {
        if(fibArr[i] % 2 !== 0) {
            result += fibArr[i]
        }
    }
    console.log(result)
    return result; 
}

1 Answers1

2

I guess you could do something like:

function sumFibs(num) {
    let a = 0, b = 1, fib = 0; 
    let i = 0; 
    let fibArr = []
    let result = 0; 

    while(fib <= num){
        fibArr.push(fib)
        a = b; 
        b = fib; 
        fib = a+b; 
    }

    for(let i = 0; i<fibArr.length; i++) {
        (fibArr[i] % 2 !== 0) ? (result += fibArr[i]) : null;
    }
    console.log(result)
    return result; 
}

But this doesn't seem to add much value, only confusion. Note that ternary operator is often used as an assignment, not a control flow statement.

To be more specific this is the part that was changed. Note that there is no way of having something like {condition} ? value : syntax wise. You always have to return an expression after the colon.

(fibArr[i] % 2 !== 0) ? (result += fibArr[i]) : null;
rnli
  • 575
  • 8
  • 16
  • So, the preferred way is to simply use if statement? – Mehmet Eyüpoğlu Apr 19 '20 at 22:27
  • Yes, it makes more sense of what you are trying to achieve. Otherwise it is unclear if you have forgot an assignment or is it intentionally left unassigned. – rnli Apr 19 '20 at 22:30
  • The purpose is to include more ES6 features for practical reasons, but it seems it is not a good thing to use them all the time. – Mehmet Eyüpoğlu Apr 19 '20 at 22:33
  • I mean, you can certainly replace the ternary with not a ternary, whether it be an if statement or a conditional operator short-circuit. `{condition} && doY()` – Kevin B Jun 03 '22 at 16:24