Search code examples
javascriptnode.jsiifeself-invoking-function

Current code needs to be IIFE(Self-Invoked) - Code works and runs


I am currently stuck as to how I can make my code IIFE, self-invoking. The problem statement is:

Your client wants to have a listing of zip codes from a zip code study (listed just once each) in order from least to greatest. He would like it to "just run" (self-invoking).

My code is displaying the correct output, where all the zipcodes are from least to greatest and are listed once. I need help understanding how to make my current code as "self-invoking". Here is my current code:

//Start.
window.onload = uniqueZipcodes;
function assignment12_3() {
    // Your code goes in here.
}

function uniqueZipcodes(){

    //Start.
    //Variables
    var records, zip;
    var output = document.getElementById("selfInvokingFunctionDiv");
    var zipcodes = [];
    var outputString = "";

    //Gets the records...
    records = openZipCodeStudyRecordSet();
    //This will loop through the records and put unique records
    //into an array
    while(records.readNextRecord()){
        zip = records.getSampleZipCode();
        if(!zipcodes.includes(zip)){
            zipcodes.push(zip);
        }
    }

    //Will sort the zipcodes
    zipcodes.sort();

    //outputs the zipcodes.
    for(var z in zipcodes){
        outputString += zipcodes[z] + "</br>";
    }

    outputDiv.innerHTML += outputString;
};

Solution

  • you can invoke it once when it first loads:

    function assignment12_3() {
        // Your code goes in here.
    }
    
    assignment12_3();  // invoke it once
    

    alternatively:

    (function assignment12_3() {
        // Your code goes in here.
    })()