How to make a function outside the loop properly

I’ve created a collection with collections inside and loop them. And I want to have one function outside the loops to call it in many cycles after it.

In the beginning of the script I declare the variables for function to use,

(function SplitByPalletsV2() {
  let MPkg;
  let MQty = 0;
  ///then I create a map

  let Pkg = new Map();
  let PQty = 0;
  Pkg.clear();
  ///... (some code for filling collection)
  ////then I loop other collection called Waybill and inside this loop the map is filled  :
  for (let [key, value] of Waybill) {
    ///...fill the Pkg map
    ///somewhere there I call the function to find max of value in this map
    MaxPackage();
  }
  function MaxPackage() {
    for (let [key6, value6] of Pkg) {
      if (Number(value6) > MQty) {
        MQty = Number(value6);
        MPkg = key6;
      }
    }
  }
})();

And it doesn’t work.

When I declare map and variables inside the collection and put a function inside the Waybill loop like this, it works:

let Pkg = new Map();
let PQty = 0;
Pkg.clear();
//filling the Pkg

let MPkg;
let MQty = 0;
function MaxPackage() {
  for (let [key6, value6] of Pkg) {
    if (Number(value6) > MQty) {
      MQty = Number(value6);
      MPkg = key6;
    }
  }
}
MaxPackage();

Though I write the code in a built-in IDE for OnlyOffice macros, I’m very limited with testing and debug instruments (no instruments at all), I don’t understand what happens -seems when I declare global variables it doesn’t work.