JavaScript Reference Error – Undefined top-level function.

I have recently done some JavaScript coding, not because I’d do it often, but just because the occasion arose. And, while doing so, I frequently obtained the error message, from my in-browser debugger, that a top-level function, which I had defined in my JavaScript, and which was to be called from within HTML elements, was simply not defined. To illustrate exactly what I mean, I’ll give my most-recent example:

 


<script type="text/javascript" src="http://dirkmittler.homeip.net/zip.js/dist/zip-full.min.js"></script>
<script type="text/javascript" src="http://dirkmittler.homeip.net/text/Brotherhood_Wolf-asciiart/viewer_z.js"></script>
</head>

<body onload="loadZip()">

 

In this case, when the body was loaded, at some point in the exercise, ‘loadZip’ did not seem to be defined.

This is a type of error which could happen to anybody – newbies and professionals alike – but, which a newbie might not understand the origin of. And, for the sake of argument, I’ll just assume for the moment, that the reader is not so much a newbie, that he or she failed to supply the file ‘viewer_z.js’, or, that within this file, he or she failed to try to define the function ‘loadZip’ (both of these being my own examples).

To understand why this error takes place, the reader should understand, that in modern browsers, JavaScript is compiled, and no longer, just interpreted. Most often this will happen, because the browser’s built-in JavaScript compiler failed to compile either an entire ‘.js’ File, or, an entire in-line script. The browser acts, as if that script had never been supplied.

Most often, this happened to me, just because I was missing a closing parenthesis somewhere. What was happening was, that the JavaScript compiler that runs in the browser was waiting for that closing parenthesis, all the way to the end of the script, and encountered the end of the script, which, in the case of in-line scripts is denoted by a closing ‘</script>’ tag, before ever finding that missing, closing parenthesis.

Next, the compiler treats the entire script, as if it had never been supplied.

On one rare occasion, the same thing happened to me, because I had put ‘await’ keywords, into a function the definition of which was not preceded by the ‘async’ keyword.

Either way, this was due to JavaScript which could not be compiled, and which was therefore ‘never defined’, as far as modern browsers are concerned.

If this is happening to my reader, then chances are, they are looking for a simple error like that, and not for anything more complex.

Continue reading JavaScript Reference Error – Undefined top-level function.