Skip to content Skip to sidebar Skip to footer

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(

Solution 1:

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.

Solution 2:

You can just return whatever a > b evaluates to.

function isAGreaterThanB(){
     return a > b;
 }

As a > b evaluates to either True or False, you can just return that value directly.

Actually doing it how you typed is, is a really bad way to do it and is unneccessarily complicated for something as basic as this.

Solution 3:

Yes it is possible, you could for example say this:

function getBiggerNumber(a, b){
    return a > b ? a : b
}

this function returns a if a is bigger than b and b if b is bigger than a. Just for completeness: It would also return b if a and b would be equal

Post a Comment for "Return Result From Ternary In One Line (javascript)"