Tests:
  • ?. operator (results in defined value)

    AخA
     
    const obj = { a: { b: { c: { exists: true } } } };
    const exists = obj?.a?.b?.c?.exists;
  • ?. operator (results in undefined value)

     
    const obj = { a: { b: { c: { exists: true } } } };
    const exists = obj?.a?.b?.c?.d?.e?.f?.g?.exists;
  • getProperty (results in defined value)

    x
     
    function getProperty(obj, ...path) {
      if (typeof obj !== 'object' || obj === null) {
        return undefined;
      }
      if (path.length === 0) {
        return obj;
      }
      let current = obj;
      for (let index = 0; index < path.length; index += 1) {
        current = current[path[index]];
        // If there is more path to traverse but the current value is not traversable, quit.
        const isArray = Array.isArray(current);
        const isObject = !isArray && typeof current === 'object' && current !== null;
        if (!isObject && !isArray && (index + 1) < path.length) {
          return undefined;
        }
      }
      return current;
    }
    const obj = { a: { b: { c: { exists: true } } } };
    const exists = getProperty(obj, 'a', 'b', 'c', 'exists');
  • getProperty (results in undefined value)

     
    function getProperty(obj, ...path) {
      if (typeof obj !== 'object' || obj === null) {
        return undefined;
      }
      if (path.length === 0) {
        return obj;
      }
      let current = obj;
      for (let index = 0; index < path.length; index += 1) {
        current = current[path[index]];
        // If there is more path to traverse but the current value is not traversable, quit.
        const isArray = Array.isArray(current);
        const isObject = !isArray && typeof current === 'object' && current !== null;
        if (!isObject && !isArray && (index + 1) < path.length) {
          return undefined;
        }
      }
      return current;
    }
    const obj = { a: { b: { c: { exists: true } } } };
    const exists = getProperty(obj, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'exists');
Rendered benchmark preparation results:

Suite status: <idle, ready to run>

Previous results

Experimental features:

  • Test case name Result
    ?. operator (results in defined value)
    ?. operator (results in undefined value)
    getProperty (results in defined value)
    getProperty (results in undefined value)

    Fastest: N/A

    Slowest: N/A

Latest run results:
Run details: (Test run date: 3 years ago)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62
Chrome 90 on Mac OS X 10.15.7
View result in a separate tab
Test name Executions per second
?. operator (results in defined value) 6208473.0 Ops/sec
?. operator (results in undefined value) 5825148.5 Ops/sec
getProperty (results in defined value) 1164066.8 Ops/sec
getProperty (results in undefined value) 1001086.1 Ops/sec