I have written a self-invoking JavaScript code:
(function assignment12_3() {
// Your code goes in here.
var records = openZipCodeStudyRecordSet(),
zipArray = [],
zipUnique = [];
while (records.readNextRecord()) {
var zips = records.getSampleZipCode();
zipArray.push(zips);
zipArray.sort();
}
for (var x = 0; x < zipArray.length; x++) {
if (zipArray[x] !== zipArray[x-1]) {
zipUnique.push(zipArray[x]);
}
}
var output = document.getElementById('outputDiv');
for (var y = 0; y < zipUnique.length; y++) {
output.innerHTML += zipUnique[y] + "<br>";
}
})();
into my html and it works perfectly, but when I put it into an external JavaScript file, I get an error of:
Uncaught TypeError: Cannot read property 'innerHTML' of null
for my:
output.innerHTML += zipUnique[y] + "<br>";
below is the link to the image with the example of the error and highlighting the line that has the error when I put the code into an external js file.
Is it not possible to put self-invoking functions (IIFE) into an external JavaScript file and use it in an html file? Why does my code work perfectly when in an HTML script tag, but not in an external JavaScript file?