LNyarla
LNyarla

Reputation: 496

Define a js function inside another js function

I've recently found this code snippet:

function start() {

    function sleep(milliSeconds) {
        var startTime = new Date().getTime();
        while (new Date().getTime() < startTime + milliSeconds);
    }

    sleep(10000);
    return "Hello Start";
}

What advantages do we have defining functions this way instead of using a 'traditional' approach?

Thanks in advance.

Upvotes: 3

Views: 164

Answers (2)

marteljn
marteljn

Reputation: 6516

The advantage to doing this is that your function sleep is no longer defined at the global scope. It is scoped to the function start.

This is advantageous because putting all of your functions at the global scope, can cause conflicts with other scripts.

There is nothing traditional about defining all functions as globals, it is just a bad practice that has been perpetuated. Reducing your global footprint is a good and responsible practice that will reduce conflicts between your scripts and other scripts that may be included in your applications.

Upvotes: 4

Cymen
Cymen

Reputation: 14419

It has to do with scope. Consider picking up a copy of the recently published Secrets of the JavaScript Ninja for a great overview of JavaScript. But we can use your browser console to try this (might not work in Internet Explorer, use Chrome):

> function start() { function bob() { console.log('bob'); } bob() };
> start()
> bob
> bob()
> ReferenceError: bob is not defined

So you can see that the function bob inside of start is not in scope outside of the start function. There are a number of reasons to do this.

Upvotes: 1

Related Questions