javascriptarraysecmascript-6optional-chainingnullish-coalescing

Is there sugar with Optional chaining/nullish coalescing to prevent Typeerrors with say Array.map?


Is there any sugar to ensure that map will not typeerror using tools like optional chaining/nullishcoalescing?

let x = {y: 1, z: 2};

x?.map(i => i); // Typeerror
Array.isArray(x)?.map(i => i); // Typeerror

let y = '1234';
y?.length && y.map(i => i) // Typeerror

Solution

  • These type errors seem to be correct. You obviously can't call map on an object literal, boolean, or string.

    If you want to optionally call map anyways, you can continue the optional chaining with ?.(params):

    
    let x = {y: 1, z: 2};
    
    x?.map?.(i => i);
    Array.isArray(x)?.map?.(i => i);
    
    let y = '1234';
    y?.length && y.map?.(i => i)
    

    Keep in mind this only checks if a property called map exists and is non-null/undefined. If it does exist but isn't a function, you'll still get an error.