is Optional Chaining Supported?

function isOptionalChainingSupported() {
    try {
        
        const obj = {};
        
        let shouldBeUndefinedIfSupported = null;

        // ❗❗❗ JavaScript CANNOT catch a SyntaxError ❗❗❗
        // --------------------------------------------------
        // ⛔ SyntaxError (if not supported)
        // const shouldBeUndefinedIfSupported = obj ?. foo;
        //    Unexpected token '.' -------------> ^

        // ⭐ eval() will cause and throw a SyntaxError if failed❗
        //    BUT won't stop the program❗
        eval(`shouldBeUndefinedIfSupported = obj ?. foo`);

        // jump to "catch" block if failed
        
        // do support
        // log(`program code just passed "eval"❗`);
        return (shouldBeUndefinedIfSupported === undefined);
        
    } catch(e) {
    
        // error has occurred, optional chaining NOT supported.
        if (e instanceof SyntaxError) {
            log(`⛔ SyntaxError: ${e.message}`);
        }
        
        return false
    }
}

💈範例:

console.log(isOptionalChainingSupported());

Last updated