Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a js function inside another js function

Tags:

javascript

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.

like image 827
LNyarla Avatar asked Jul 09 '26 09:07

LNyarla


2 Answers

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.

like image 160
marteljn Avatar answered Jul 11 '26 23:07

marteljn


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.

like image 35
Cymen Avatar answered Jul 11 '26 22:07

Cymen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!