Josh S. Josh S. - 13 days ago 5
Javascript Question

Event listener will call a function but not a variable assigned to a function

Problem - call a function whenever the browser is resized.

Incorrect Solution:

window.addEventListener("resize", resize);

var resize = function() {
console.log("message");
};


Correct Solution:

window.addEventListener("resize", resize);

function resize() {
console.log("message");
};


Question - why does the first example not work?

Answer

Function declarations are hoisted.

Assignments are not hoisted.

Since window.addEventListener("resize", resize); appears before you = function ..., the value of resize is still undefined.

This would work:

var resize = function() {
    console.log("message");
};

window.addEventListener("resize", resize);