Function expression

Isabell
Isabell used Ask the Experts™
on
Hi,

I have the following code that reads the text from a text file.

document.getElementById('button1').addEventListener('click', loadData);

const loadData = function () {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'test.txt');
  xhr.onload = function () {
    if (this.status === 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window


When I ran this and clicked button1, I got the following error:
test3.js:1 Uncaught ReferenceError: Cannot access 'loadData' before initialization

Open in new window


And I think that I know where this error came from.
I think that the reason is I am using function expression and this is not hoisted.
But maybe I don't understand 100% here.
But I suspect that even before I click the button1, when JS engine scanned my code, since 'loadData' is not hoisted, it can't access to 'loadData' at line 1.
Is this correct? I know that if I change it to the regular function, then it works.

however, at line 1, we don't try to access loadData, do we?  I thought that we try to access 'loadData' when we "click" the button1.
Please explain this to me.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Analyst Assistant
Commented:
You are correct, when you use a function expression the function is not hoisted.

Have you tried simply moving the code in line 1 below the function expression?
ste5anSenior Developer

Commented:
"hoisted"?

It's simply not defined at this time in your current scope. Either change the "time", thus the order:

const loadData = function () {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'test.txt');
    xhr.onload = function () {
        if (this.status === 200) {
            document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
        }
    }

    xhr.send();
}

document.getElementById('button1').addEventListener('click', loadData);

Open in new window

or you change the scope. E.g.

document.getElementById('button1').addEventListener('click', function () {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'test.txt');
    xhr.onload = function () {
        if (this.status === 200) {
            document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
        }
    }

    xhr.send();
});

Open in new window

NorieAnalyst Assistant

Commented:
stefan

If the code is written like this the function is 'hoisted' and is available.
document.getElementById('button1').addEventListener('click', loadData);

function loadData () {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'test.txt');
  xhr.onload = function () {
    if (this.status === 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

ste5anSenior Developer

Commented:
I'm not a native speaker (German indeed), and any dictionary does not provide a meaningful translation for hoisted. Nor did I ever stumbled upon this term in over 25 years..

Do you have an link to an explanation?
NorieAnalyst Assistant

Commented:
Wasn't too sure about the term myself when I first saw it used, think I've seen similar concepts in other languages under different names.

Anyway, don't know if it'll help but here's a link with a half decent explanation - Understanding Hoisting in Javascript.
leakim971Multitechnician
Top Expert 2014

Commented:

Author

Commented:
Thank you guys!!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial