Alternatives to the ternary function

Let's suppose that you have this function:

jsx

const sendMail = (recipient) => {
    
    // Result variable
    let res;
    
    // If exists the recipient, returns ok
    if(recipient) res = '👌';
    
    // Returning the result
    return res;
  
}

Applying ternary logic, the function can be translated as:

jsx

const sendMail = (recipient) => {
    
    // Result variable
    let res;
    
    // If exists the recipient, returns ok
    res = recipient ? '👌' : res;
    
    // Returning the result
    return res;
  
}

Lastly, applying short circuit logic, the function can be translated as:

jsx

const sendMail = (recipient) => {
    
    // Result variable
    let res;
    
    // If exists the recipient, returns ok
    recipient && res = '👌';
    
    // Returning the result
    return res;
  
}

Short circuit logic is useful when the second condition of the ternary function returns null.

In the last case, the first condition is checked, in case recipient is true, second condition is checked and 👌 is assigned.

If first condition is false, second condition won't be checked and, therefore, 👌 won't be assigned.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.