Reputation: 113
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?
Upvotes: 0
Views: 208
Reputation: 829
Because in the second example Function Hoisting
is taking place. A function declaration like this hoists the function's name and its definition.
function someFunction(){
//Some Code
}
By doing this, the JavaScript interpreter allows you to use the function before the point at which it was declared in the source code.
So, even if your function definition comes after, you can still use it, as it is hoisted.
However, function definition hoisting only occurs for function declarations, not function expressions. For Example:
var definitionNotHoisted = function () {
console.log("Definition not hoisted!");
};
This function can only be used after it is defined. That is why in the first example, function does not work.
You can know more about Function Hoisting
here.
Upvotes: 1
Reputation: 386540
The first is in this order executed,
var resize; // undefined
window.addEventListener("resize", resize);
resize = function() {
console.log("message");
};
the value of resize
is at the time where the eventlistener is set, undefined
.
The variable becomes hoisted, that means, the variable is declared, but does not have an assignment.
The second is in this order executed,
function resize() {
console.log("message");
}
window.addEventListener("resize", resize);
because function declarations are hoisted, too.
Upvotes: 0
Reputation: 943142
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);
Upvotes: 2