Take the 2-minute tour ×

I've recently found this code snippet:

function start() {

    function sleep(milliSeconds) {
        var startTime = new Date().getTime();

    return "Hello Start";

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

Thanks in advance.

share|improve this question
What do you mean by traditional approach? One function inside another simply works in a different scope. –  VisioN Feb 13 '13 at 16:27
The real question is why wouldn't you use timeout –  Austin Feb 13 '13 at 16:34
@VisioN for example in java is not possible to define a method inside another, unless using anonymous methods. –  LNyarla Feb 13 '13 at 16:43

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer


