Saravana
Saravana

Reputation: 40594

Why does JavaScript allow function declarations after the return statement?

JavaScript allows this:

function outside() {
    inside();
    return 44;

    function inside() {
        console.log("inside");
    }
}

When outside is called the output is:

inside
44

Why does this work and why doesn't it work for other statements like the one below:

function outside() {
    return 44;
    console.log("inside");
}

which just prints 44.

Upvotes: 0

Views: 244

Answers (5)

Felix Kling
Felix Kling

Reputation: 816462

What you see is the effect of hoisting. When a function is about to be executed, all the variable and function declarations are evaluated first, before the function is really executed. Thus your first function is equivalent to

function outside() {
    function inside() {
        console.log("inside");
    }
    inside();
    return 44;
}

Details can be found in the specification, 10.4.3 Entering Function Code and 10.5 Declaration Binding Instantiation.

Why does JavaScript allow function declarations after the return statement?

Why the language is defined like this can probably only be answered by Brendan Eich.

Upvotes: 2

deceze
deceze

Reputation: 522110

Because the file is parsed first and function definitions are read at that time. You are calling the function before you return, so that works just fine. Most programming languages allow you to define functions after calling them, because they all work in two steps: parsing and execution.

Upvotes: 2

iConnor
iConnor

Reputation: 20189

Function declaration:

function myName() {

}

Function Expression:

var myName = function() {

};

These are very different, the function declaration (1) is defined when the Javascript is parsed, and not when it is executed. whereas the function expression (2) is defined when the Javascript is executed.

So technically it is not being defined after the return statement.

At least this is how I understand it.

Upvotes: 0

user3007735
user3007735

Reputation: 159

function outside() {
inside(); //calling inside();
return 44;

function inside() {
    console.log("inside");
}
} 

but here

function outside() {
return 44;
console.log("inside");
}

you are just returning not calling inside() at all.

Upvotes: 0

Srinath Mandava
Srinath Mandava

Reputation: 3462

In the first case first the function inside is executed and then it comes to return..so it returns 44..

But in the second case the outside function first encounters return which means to exit from that function no matter what is return below... so it only prints 44

Upvotes: 0

Related Questions