title: Javascript | Node.js - Can't set global var inside callback
body: <p>So I got this code to get the correct COM name:   </p>
  
  <pre><code>//serialport lib import
  var serialport = require("serialport");
  
  //global var
  var prt;
  
  serialport.list(function (err, ports) {
    ports.forEach(function (port) {
      //this does NOT work.
          prt = port.comName);
        });
      });
  
  console.log(prt); //outputs UNDEFINED
  </code></pre>
  
  <p>The problem is that wherever I try to set prt to some value inside the .list()'s scope. It doesn't set the variable.</p>
  
  <p>I can however call global functions. Which really doesn't make any sense to me.</p>
  
  <pre><code>//serialport lib import
  var serialport = require("serialport");
  
  //global var
  var prt;
  
  //global function
  var printPort = function(port){
    console.log(port);
  }
  
  serialport.list(function (err, ports) {
    ports.forEach(function (port) {
      //this does NOT work.
      prt = port.comName);
      //and this DOES
      printPort(port.comName); //outputs "COMx"
    });
  });
  </code></pre>
  
  <p>I now that this is a scope related problem of course. I'm quite new to this, and quite confused about this behaviour. The fact that I can call the global function BUT I can't set the global variable doesn't make any sense to me.</p>
  
  <p>Another last question would be how to make a function out of this that RETURNS the port name. Since it's async I can't return it.</p>
  
  <p>Thank you very much.</p>