Function first called, then defined?

In the following code (example taken from here, run here), the function seems to be called before it was defined. Being new to Javascript, I would expect this to cause some kind of reference error:

var numbers = [65, 44, 12, 4];

function myFunction(item, index, arr) {
  arr[index] = item * 10;

However, it runs just fine. How does this work?

Because the function is a declaration, not an expression (anonymous function) it is hoisted totally in tact so is callable from above or below.

To elaborate, consider the following two function expressions

const foo = function (x) {
    return x * 2 + 1;
const bar = x => x * 2 + 1;

Both do the exact same thing, but neither can be called from above their position in the source listing. Only the names foo and bar are hoisted to top of scope. The expressions get evaluated on their first call.

1 Like