I got a fairly standard init function passed to a variable.
var initFunction = function()...
It's the same like "function initFunction(){}", isn't it? (internal, JavaScript creates a variable as well)
If I declare a function variable in my init function, and call it before it's declaration, it must be accessible due to the fact that all definitions (var's) in a function are initialized at first. That's what I thought is in JS's nature.
The following code doesn't work (innerFunction is undefined)
var initFunction = function(){
if(0 == 0){
innerFunction();
}
var innerFunction = function(){
alert("Hello World");
};
};
initFunction();
By the way: Is it good practice to close all function's with a semicolon?
Best regards
-
It's not good practice to close all function's with a semicolon. You are not closing your function with a semicolon in your example, but you are closing an assignment in your example (var myFunc=function(){}; just like var i=0;)John Smith– John Smith2016年05月04日 08:35:28 +00:00Commented May 4, 2016 at 8:35
-
You can define innerFunction at the end only if it get called later like with a asynchronous callback.Walfrat– Walfrat2016年05月04日 08:35:41 +00:00Commented May 4, 2016 at 8:35
-
"It's the same like "function initFunction(){}", isn't it?" - No, they're different. (Look up function expressions and function statements)evolutionxbox– evolutionxbox2016年05月04日 08:43:46 +00:00Commented May 4, 2016 at 8:43
2 Answers 2
The problem here is called Variable Hoisting. When you do:
var innerFunction = function(){
alert("Hello World");
};
The calling time will have:
var innerFunction = null; // Or undefined may be.
Then after the definition, it gets defined. Whereas, when you replace your code with:
if (0 == 0) {
innerFunction();
}
function innerFunction() {
alert("Hello World");
} // Notice no semi colon.
The whole function gets defined in the first place. If you wanna use function expressions, and not declarations, you need to take the definition to the top of the call.
Now this would work.
var initFunction = function(){
var innerFunction = function(){
alert("Hello World");
};
if (0 == 0) {
innerFunction();
}
};
Is it good practice to close all function's with a semicolon?
For function expressions, yes it is a good practise. For normal function declarations (using function keyword and not an anonymous function), it is not necessary.
Comments
It's the same like "function initFunction(){}", isn't it? (
No. Function declarations are hoisted. Function expressions are not. (You have a function expression).
You try to call innerFunction(); before a value is assigned to innerFunction (two lines later).