The Javascript IIFE prohibits accessing a variable before it has been initialized

I encountered an error message saying "Uncaught ReferenceError: Cannot access 'Q12' before initialization" while working in the changeCssClassIfOldAndNewValuesAreDifferent function. Any thoughts on what might be causing this issue? Thank you.

const formController = (function () {
                return {
                    'changeCssClassIfOldAndNewValuesAreDifferent': changeCssClassIfOldAndNewValuesAreDifferent
                };

                const formScope: any = $("form#userAnswerForm");
                const Q12: any = $('.persistable[id=Q12]', formScope);
                const Q23: any = $('.persistable[id=Q23]', formScope);

                function changeCssClassIfOldAndNewValuesAreDifferent() {
                    $('input.persistable, select.persistable').not(Q12) //<---Reference Error
                        .each(function () {
                            console.log('each persistable input and select listeners (change, mouseout)');
                            const thisPersistable: any = $(this);
                            const Q12_or_Q23_is_not_empty: boolean = !commonUtility.isEmpty(Q12) &&
                                !commonUtility.isEmpty(Q23);
                            ...
                            ...
                        });
                }
            })();

            $(function(){
                formController.changeCssClassIfOldAndNewValuesAreDifferent();
            });

Answer №1

To solve the issue, remember to move the declaration before the return statement because the function called in return tries to access Q12 which is declared after the return.

const formController = (function () {
    const formScope: any = $("form#userAnswerForm");
    const Q12: any = $('.persistable[id=Q12]', formScope);
    const Q23: any = $('.persistable[id=Q23]', formScope);

    return {
      'changeCssClassIfOldAndNewValuesAreDifferent': changeCssClassIfOldAndNewValuesAreDifferent
    };
    
    function changeCssClassIfOldAndNewValuesAreDifferent() {
        $('input.persistable, select.persistable').not(Q12) //<---Reference Error
        .each(function () {
            console.log('each persistable input and select listeners (change, mouseout)');
            const thisPersistable: any = $(this);
            const Q12_or_Q23_is_not_empty: boolean = !commonUtility.isEmpty(Q12) && 
            !commonUtility.isEmpty(Q23);
            ...
            ...
        });
    }
})();

$(function(){
    formController.changeCssClassIfOldAndNewValuesAreDifferent();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

Challenges with the Express server console

I have configured an Express Server and everything appears to be functioning correctly. The content I send is rendered in the browser, and my console.log test statements are being displayed in the terminal. However, when I inspect the browser page, nothi ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Tips for incorporating user-entered data from a text box into a JavaScript function and utilizing a loop

Although my code is functioning correctly, I am looking to make some adjustments but seem to be struggling to achieve the desired outcome. Essentially, I have two labels and an input field in which the user is prompted to enter a specific number of weeks ...

AngularJS dynamically updates the minimum date in a datepicker

My controller dynamically sets a minimum date which I retrieve as 'setmax'. I want to assign this value to my datepicker mindate. I have attempted to do this by using the following code: $scope.minDate = $scope.setmax; inside my controller. U ...

A function that retrieves the empty values from an array and returns undefined if there

After undergoing a time-consuming process, the sample below shows that the array values are returned empty. function myFunction() { let myArray = []; let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0] pastArray.forEach(item =>{ setTimeout(function(){ myA ...

The error message "Each item within a list must be assigned a unique 'key' prop" is being displayed

At the moment, I'm immersed in a project that utilizes React, Next.js, and Ant-Design. However, during the development process, I encountered an error due to the absence of a unique key like so: Here's the detailed log of the error: Warning: Ea ...

The functionality of jQuery is not functioning properly on dynamically created identical divs

I am currently working on creating a comment reply section. I have managed to load the same div for reply that I use for commenting by utilizing $('#1').append($('.enterComment').html());. In this case, 1 represents the id of the div th ...

What is the best way to execute my node script with a shell script file?

Currently, I'm working on a personal website using node to help me organize the ebooks I'm reading. Right now, my process involves moving to the project folder and running node server.js. I had an idea to create a shell script so that all I hav ...

"Modify the value of an element in an array to an object

Seeking to employ the immutability-helper addon, I am trying to modify the value of a specific key within an array. The code snippet in question is as follows: class StorageForm extends Component { constructor(props) { super(props); this.state ...

jQuery AJAX Triggered Only Once in Callback Function

I am facing an issue with the jQuery get function within my updateMyApps. The function works fine when called directly after it is declared. It successfully loops through the data and appends elements to the DOM. However, when I submit the form #addapplic ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

Overriding NavLink in React Bootstrap with custom CSS doesn't work as expected

Recently diving into the world of React and Bootstrap, I decided to experiment with them by using react-bootstrap. It was mentioned that a simple way to override Bootstrap CSS is to apply your own CSS on top of it. So here's what I've been workin ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

An error was encountered: Component.setState is undefined and cannot be read, leading to a TypeError

Could the error be caused by the fact that the Counter component remains at a count of 0, with this not bound anywhere? class Counter extends React.Component { constructor(props) { super(props) this.state = { count: 0 ...

Error encountered: When implementing mergeImages in express.js, a ReferenceError occurs stating that the window is not

I am encountering an issue while using mergeImages on my express.js server. The error message "ReferenceError: window is not defined" is displayed, but I am puzzled because I have not used the word 'window' in my code at all. Could you please rev ...

How to conditionally import various modules in Next.js based on the environment

Having two modules 'web,ts' and 'node.ts' that share similar interfaces can be challenging. The former is designed to operate on the client side and edge environment, while the latter depends on node:crypto. To simplify this setup, I a ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...