Search code examples
javascriptloopsif-statementternary

Is it possible to write one way ternary operator?


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; 
}


Solution

  • 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;