-3

I'm not sure how to make this function into a self-invoking function. My code is looping through an array of zip codes from a JS file and sorting it from smallest to biggest and outputting it. I've found online that adding "())" at the end of the newZipCodeArray function, is supposed to self-invoke the function. However, it's not working. What am I doing wrong?

[enter image description here][1]

// Global variable
var zipCodeArray = [];

(function newZipCodeArray(currentZipCode) {

    var valueFound = false;
    for (zipCodeIndex = 0; zipCodeIndex <= zipCodeArray.length; zipCodeIndex++) {
        if (currentZipCode === zipCodeArray[zipCodeIndex]) {
            valueFound = true;
        }
    }
    if (valueFound === false) {
        zipCodeArray.push(currentZipCode);
    }
}());

function newZipCodeArrayssignment12_3() {
    // Instantiate variables.
    var output;
    var zipCodeRecords;

    // Get the element.
    output = document.getElementById('outputDiv');

    zipCodeRecords = openZipCodeStudyRecordSet();

    // Call the function to read the next record.
    while (zipCodeRecords.readNextRecord()) {
        currentZipCode = zipCodeRecords.getSampleZipCode();
        newZipCodeArray(currentZipCode);
    }

    // Sort the zip code array.
    zipCodeArray.sort();
}
Pointy
  • 371,531
  • 55
  • 528
  • 584
T. Meister
  • 21
  • 2

1 Answers1

1

The syntax involved in immediately-invoked (or self-invoked) functions doesn't allow it to be invoked from elsewhere. The IIFE pattern is intended to be used when the function only needs to be invoked once.

Note:

The grouping parenthesis wrapping the function change it from a declaration to an expression. And, as an expression, its name won't be added to the surrounding scope for other code to reference.

To invoke newZipCodeArray once right away and allow for it again later, you'll want to remove the parenthesis from around it and call it by name in a separate statement:

newZipCodeArray(); // first call

function newZipCodeArray(currentZipCode) {
    // ...
}

function newZipCodeArrayssignment12_3() {
    // ...

    while (zipCodeRecords.readNextRecord()) {
        // ...
        newZipCodeArray(currentZipCode); // additional calls
    }

    // ...
}
Community
  • 1
  • 1
Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193