[JavaScript] Conditional (Ternary) Operator

Can be used as a one line if-else expression. Syntax:

condition ? expression-if-true : expression-if-false;

function checkEqual(a, b) {
    return a == b ? "Equal" : "Not Equal";
}

/* Chain them together to check for multiple conditions */
function checkSign(num) {
    return (num == 0) ? "zero"
        : (num > 0) ? "positive"
        : "negative";
}

/* If there is no "else", just write */
function checkEqual(a, b) {
    if (a == b) return "Equal";
}
console.log(checkEqual(1, "1"));

Leave a Reply

Your email address will not be published. Required fields are marked *