Friday, June 1, 2018

Javascript - Nesting function is good?

Nay! .. so far my reading goes, it is not . The reason is that in Javascript, every function is a value. with nested functions,

In a setup like below,

function foo(a, b) {
    function bar() {
        return a + b;
    }
    return bar();
}

foo(1, 2);

An outer function, foo(), contains an inner function, bar(), and calls that inner function to do work. Many developers forget that functions are values in JavaScript. When you declare a function in your code, the JavaScript engine creates a corresponding function object—a value that can be assigned to a variable or passed to another function. The act of creating a function object resembles that of any other type of value; the JavaScript engine doesn't create it until it needs to. So in the case of the above code, the JavaScript engine doesn't create the inner bar() function until foo() executes. When foo() exits, the bar() function object is destroyed.

The fact that foo() has a name implies it will be called multiple times throughout the application. While one execution of foo() would be considered OK, subsequent calls cause unnecessary work for the JavaScript engine because it has to recreate a bar() function object for every foo() execution. So, if you call foo() 100 times in an application, the JavaScript engine has to create and destroy 100 bar() function objects. Big deal, right? The engine has to create other local variables within a function every time it's called, so why care about functions?

references:
https://code.tutsplus.com/tutorials/stop-nesting-functions-but-not-all-of-them--net-22315

No comments:

Post a Comment