Is there a JavaScript idiom to change "undefined" to "null"?

This is a fairly old question and probably my answer is a little late, but I decided for myself in the following way:

const valueOrNull = (value = null) => value;

const a = { d: '' };
valueOrNull(a.b?.c) === null; // true
valueOrNull(a.d) === '';      // true
valueOrNull() === null;       // true

Any undefined value will get null as the default value;


undefined || null - or any falsey || null - will return null


Javascript now supports a null-coalescing operator: ??. It may not be production-ready (consult the support table), but it's certainly safe to use with Node or a transpiler (TypeScript, Babel, etc.).

Per MDN,

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Much as || can provide a "default" value when the left operand is falsey, ?? provides a "default" value if the left operand is null or undefined. You can use this to coerce undefined to null:

    // OR operator can coerce 'defined' values
    "value"   || null;    // "value"
    0         || null;    // null
    false     || null;    // null
    ""        || null;    // null
    undefined || null;    // null
    
    // The null-coalescing operator will only coerce undefined or null
    "value"   ?? null;    // "value"
    0         ?? null;    // 0
    false     ?? null;    // false
    ""        ?? null;    // ""
    undefined ?? null;    // null

An example based on the question:

    function mustNotReturnUndefined(mightBeUndefined) { // can return null
        // Substitute empty string for null or undefined
        let result = processValue(mightBeUndefined ?? "");

        // Substitute null for undefined
        return result ?? null;
    }