Home > Software engineering >  Ternary short circuit vs If short circuit in JavaScript
Ternary short circuit vs If short circuit in JavaScript

Time:12-06

I am trying to short circuit the code to return false with a ternary operator. My understanding was that the ternary had an implicit return and in this case would have the same result as the if statement below it. That would be to immediately return false if the two arrays.length do not match and to pass onto the following logic if they did. I would appreciate some explanation as I have tried to understand the difference but it does not make sense to me why this would not work. `

function same(arrOne, arrTwo) {
// This ternary and if statement should do the same thing?

    // arrOne.length !== arrTwo.length ? false : {}

    if (arrOne.length !== arrTwo.length) {
        console.log(false)
        return false
    }

    let result = {}
    // append frequencies of numbers to result object
    arrOne.forEach((i) => {
        result[i] ? result[i]   : (result[i] = 1)
    })
    // check to see if square matches root in object
    arrTwo.forEach((i) => {})
    console.log(result)
}

same([1, 2, 3, 4], [4, 1, 9]) // false lengths do not match
// same([1,2,3], [1,9]) // false
// same([1,2,1], [4,4,1]) // false frequency must be the same

`

I have tried to short circuit the function to return false with a ternary operator that tests the length of the two arrays taken as arguments if their lengths do not match. The code runs as if the ternary is doing nothing.

CodePudding user response:

The ternary operator does not implicitly return. Only a return statement returns from a function.

What you are probably confusing is that a ternary operator returns a value. As in, you can assign the result of a ternary expression to something:

var foo = bar ? 'baz' : 42;

This is what it means for the ternary operator to return a value. This does not mean that it will implicitly execute a return and stop a function from processing. It just returns a value the same way 1 2 returns a value (3).

A ternary operator isn't useful to conditionally return from a function. Even if a ternary expression would do what you think it does, it would always have to return or never; but you want to return only in certain conditions. E.g. with a ternary you can only do this:

return foo ? bar : baz;

You can decide what to return inline, you cannot decide whether to return or not.

  • Related