1

Before writing this question I read Can we call the function written in one JavaScript in another JS file? and Calling a JavaScript function in another js file but still cannot fix my issue.

I am getting the error message - Uncaught ReferenceError: getLocaleDateString is not defined.

The file that contains the function is being loaded before the file that needs the function.

When I copy the contents of getLocaleDataString.js into sys.datepicker.js everything works fine, but the code then starts to look messy and is hard to navigate.

reigster4.html

<body>
    <script src='{% static "getLocaleDateString.js" %}'></script>
    <script src='{% static "sys.datepicker.js" %}'></script>
</body>

getLocaleDataString.js

    (function ($) {



  function getLocaleDateString() {

 
    const formats = {
          "af-ZA": "yyyy/MM/dd",
          "zu-ZA": "yyyy/MM/dd",
    };

    return formats[navigator.language] || "dd/MM/yyyy";
  } //end of getLocaleDateString


  
})

sys.datepicker.js

 function formatDate(year, month, day) {
    let str = (navigator.language, getLocaleDateString());

    return(str)
  
  } 

Update - getLocaleDataString.js

I changed the code to this

  function getLocaleDateString() {


const formats = {
      "af-ZA": "yyyy/MM/dd",
      "zu-ZA": "yyyy/MM/dd",
};

return formats[navigator.language] || "dd/MM/yyyy";


} //end of getLocaleDateString

Simply commenting out the rouge code did not work. I had to physically delete it.

Now everything is working correctly.

Ross Symonds
  • 690
  • 1
  • 8
  • 29
  • 6
    `getLocaleDateString` is not global, it's defined inside the anonymous function and doesn't exist outside of it. As [the accepted answer](https://stackoverflow.com/a/25963012/218196) in the second question says: *"A function cannot be called unless it is in the same or greater scope then the one trying to call it."* There doesn't seem to be a need for the `(function($) { ... })` wrapper, so just remove it. – Felix Kling Sep 30 '21 at 13:22
  • 1
    move it outside the iife and do `const formats = { "af-ZA": "yyyy/MM/dd", "zu-ZA": "yyyy/MM/dd" }; const getLocaleDateString = () => formats[navigator.language] || "dd/MM/yyyy";` – mplungjan Sep 30 '21 at 13:26
  • 1
    `but the code then starts to look messy`, If you want clean JS, I would strongly suggest you look into modules,. Either ES6 modules, or use a bundler like webpack etc. The fix pointed out by @FelixKling will start to pollute the global, and that's not ideal, especially if you want your app to grow.. – Keith Sep 30 '21 at 13:29

0 Answers0