DEV Community 👩‍💻👨‍💻

Discussion on: How Ternaries Can Improve Your JavaScript Conditionals

Collapse
 
unchar1 profile image
Askara Novaru

To me ternaries look cool, but end up making the code denser than it needs to be. Normally for stuff like


function work() {
    ....
    let cartItemCount = 0;

    if (user.isAuthenticated) {
        cartItemCount = fetchCountFromDB(user);
    } else {
        cartItemCount = 0;
    }
    ....
}

I'd just move it to a function,


function work() {
    ....
    let cartItemCount = getItemCount(user);
    ....
}

function getItemCount(user) {
    if (!user.isAuthenticated) {
        return 0;
    }
    return fetchCountFromDB(user);
}

This is a bit more code, but easier for me to come back to later.

Collapse
 
codemouse92 profile image
Jason C. McDonald

That is generally good, as long as you don't slide into DRY spaghetti. If you only use it once, it seldom belongs in its own function. In your example, getItemCount() is a good candidate however, as it makes sense you may need it elsewhere.

If performance matters, you also need to be careful about instruction cache misses, which occur when calling a function in an altogether separate area of the code. These are fine in moderation, but can become a problem when you're jumping that gap hundreds or thousands of times a second. (When this starts mattering, use a proper code profiler to determine the problem.)