Search code examples
javascriptshorthandternary

Return result from Ternary in one line (JavaScript)


In JavaScript, rather than having to assign the result to a variable, is it possible to return the result of a ternary in one line of code?

e.g. Instead of this:

function getColor(val){
    var result = val <= 20 ? '#000' : val >= 80 ? '#999' : '#555';
    return result;
}

Can we do something like this...

function getColor(val){
    return val <= 20 ? '#000' : val >= 80 ? '#999' : '#555';
}

I am asking this because I just tried the above and nothing was returned.


Solution

  • Yes. It's possible. Also you can make your code even more compact.

    function isAGreaterThanB(){
        return a > b;
    }
    

    Above code will return true if a is greater, false if not.