Patrik
Patrik

Reputation: 1129

Function declaration undefined - Why?

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

Upvotes: 0

Views: 308

Answers (2)

Quentin
Quentin

Reputation: 943999

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).

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

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.

Upvotes: 4

Related Questions