javascriptjavascript-objectsnull-coalescinglogical-or

Null coalescing string and conditional string via logical OR-operator results in number


Null coalescing by ORing a string (via PRIORITIES[NUM_TO_PRIORITY[priorityNum]] where priorityNum is input) and a string (via conditional Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low) should output a string yet outputs a number (matching the input). Why does this happen?

This could be a js quirk but unsure why the output is a number as testing shows coalescing should be between 2 strings to output a string:

const PRIORITIES = {
    high: 'HIGH',
    low: 'LOW',
};
const NUM_TO_PRIORITY = {
    0: 'high',
    1: 'low',
};
const priorityNum = 0;
console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]]); // "HIGH"
console.log(Object.values(PRIORITIES).includes(priorityNum)); // false
console.log("HIGH" || false) // "HIGH" <- Expected output

// Based on the above code, the following code should output "HIGH" yet outputs 0, why does this happen?
console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]] || Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low);


Solution

  • || has higher operator precedence than ?, so your code is evaluated as

    (PRIORITIES[NUM_TO_PRIORITY[priorityNum]] || Object.values(PRIORITIES).includes(priorityNum))  ? priorityNum : PRIORITIES.low
    

    const PRIORITIES = {
        high: 'HIGH',
        low: 'LOW',
    };
    const NUM_TO_PRIORITY = {
        0: 'high',
        1: 'low',
    };
    const priorityNum = 0;
    console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]]); // "HIGH"
    console.log(Object.values(PRIORITIES).includes(priorityNum)); // false
    // "HIGH" || false // "HIGH" <- Expected output
    
    // Based on the above code, the following code should output "HIGH" yet outputs 0, why does this happen?
    console.log(PRIORITIES[NUM_TO_PRIORITY[priorityNum]] || Object.values(PRIORITIES).includes(priorityNum) ? priorityNum : PRIORITIES.low);