HomeToolsAbout a20k

Conditional and Comparison

Conditional

Ternary operator

Operator is frequently used as an alternative to an if...else statement

condition ? exprIfTrue : exprIfFalse

Example

function getFee(isMember) { return isMember ? '$2.00' : '$10.00'; } console.log(getFee(true)); // Expected output: "$2.00" console.log(getFee(false)); // Expected output: "$10.00" console.log(getFee(null)); // Expected output: "$10.00"

Conditional Chain

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain

function example() { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // equivalent to function example() { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } }

Comparison

Comparing whether more than 3 elements are equal to each other?

Comparison logic for up to three elements is straightforward. Comparing more elements need more clever solutions.

/* manual comparison of 3 elements */ if(g === h && g === f) { "do something" } /* looping comparison of n-elements */ function nEqual(){ for (let i = 1; i < arguments.length; i++){ if ( arguments[i] === null || arguments[i] !== arguments[i-1] ) { return false; } return true; }; nEqual(a,b,c,d,e,f,g,h) && { "do something" }
© VincentVanKoh