Search code examples
javascriptglobal-variablesuncaught-reference-error

Uncaught ReferenceError: mahi is not defined


i am getting error massage when i am trying to pass value between two functions here is a error "Uncaught ReferenceError: mahi is not defined" i have it defined and asigned at line no 121 still am facing error

   function encode() {
        var selectedfile = document.getElementById("cimg").files;
        if (selectedfile.length > 0) {
            var imageFile = selectedfile[0];
            var fileReader = new FileReader();
            fileReader.onload = function (fileLoadedEvent) {
                var srcData = fileLoadedEvent.target.result;  
                window.mahi = srcData; // here i have been defined variable as mahi
                console.log(mahi)   // here is variable work                
            }
            fileReader.readAsDataURL(imageFile);
        }
    }

    console.log(mahi) //here is a error "Uncaught ReferenceError: mahi is not defined" i have it defined and asigned at line no 121 stilli am facing error

Solution

  • Because when you call console.log(mahi) outside the encode(), the variable wasn't declared yet.