title: Javascript Return Variable across Different Files
body: <p>I am trying to build a web app that allows users to call each other. Currently, I am trying to implement a voice recognition feature that does the following:</p>
  <blockquote>
  <p>The voice recognition starts when the call is connected. It recognizes
  and constantly populates a variable with the recognized text as the call progresses. When the call is terminated, return the variable
  containing the final transcribed text.</p>
  </blockquote>
  <p>In one of my HTML files, I am calling two JS files in the following order:</p>
  <pre><code>  &lt;script src=&quot;/resource/js/chat/call.js&quot; defer&gt;&lt;/script&gt;
    &lt;script src=&quot;/resource/js/chat/voice_recognition.js&quot; defer&gt;&lt;/script&gt;
  </code></pre>
  <p>In <code>voice_recognition.js</code>, I have a voice recognition function that translates what a user speaks into text, and populates the text into the variable.</p>
  <pre><code>function start_transcript(variable_to_populate) {
    var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
    var recognition = new SpeechRecognition();
  
    recognition.onresult = function(event) {
      for (var i = event.resultIndex; i &lt; event.results.length; ++i) {
        if (event.results[i].isFinal) {
          variable_to_populate += event.results[i][0].transcript;               
        }
      }
    }
  }
  </code></pre>
  <p>In the <code>call.js</code> function, I am using an API that could detect when a call is initiated and disconnected. I have the following codes inside <code>call.js</code></p>
  <pre><code>var final_transcript = &quot;&quot;;
  device.on(&quot;connect&quot;, function(conn) {
    start_transcript(final_transcript);
  })
  
  device.on(&quot;disconnect&quot;, function(conn) {
    console.log(final_transcript);
  })
  </code></pre>
  <p>But the <code>final_transcript</code> logged empty after call terminates even though there has been voice recognition going on. Is there anything wrong with my approach of declaring a global variable called <code>final_transcript</code> and passing to the <code>voice_recognition</code> function to populate the variable? Also, is there a better approach you can think of to solve this problem?</p>