title: Do javascript engines optimize constants defined within closures?
body: <p>Imagine I have a function which accesses a constant (never mutated) variable (lookup table or array, for example). The constant is not referenced anywhere outside the function scope.
  My intuition tells me that I should define this constant outside the function scope (<strong>Option A</strong> below) to avoid (re-)creating it on every function invocation, but is this really the way modern Javascript engines work? I'd like to think that modern engines can see that the constant is never modified, and thus only has to create and cache it once (<em>is there a term for this?</em>). Do browsers cache functions defined within closures in the same way?</p>
  
  <p>Are there any non-negligible performance penalties to simply defining the constant inside the function, right next to where it's accessed (<strong>Option B</strong>)? Is the situation different for more complex objects?</p>
  
  <pre class="lang-js prettyprint-override"><code>// Option A:
  function inlinedAccess(key) {
    const inlinedLookupTable = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
    }
  
    return 'result: ' + inlinedLookupTable[key]
  }
  
  // Option B:
  const CONSTANT_TABLE = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
  }
  function constantAccess(key) {
    return 'result: ' + CONSTANT_TABLE[key]
  }
  </code></pre>
  
  <h2>Testing in practice</h2>
  
  <p>I created a <strong><a href="https://jsperf.com/constant-object-caching/" rel="noreferrer">jsperf test</a></strong> which compares different approaches:</p>
  
  <ol>
  <li><code>Object</code> - inlined (option A)</li>
  <li><code>Object</code> - constant (option B)</li>
  </ol>
  
  <p>Additional variants suggested by <a href="https://stackoverflow.com/a/58436106/1527562">@jmrk</a>:</p>
  
  <ol start="3">
  <li><code>Map</code> - inlined</li>
  <li><code>Map</code> - constant</li>
  <li><code>switch</code> - inlined values</li>
  </ol>
  
  <p><strong>Initial findings (on my machine, feel free to try it out for yourself):</strong></p>
  
  <ul>
  <li>Chrome v77: (4) is by far the fastest, followed by (2)</li>
  <li>Safari v12.1: (4) is slightly faster than (2), lowest performance across browsers</li>
  <li>Firefox v69: (5) is the fastest, with (3) slightly behind</li>
  </ul>