Function returned from another function

62 views Asked by At

I observed a difference in output when trying to run similar function.

function func1(){
     function sum(){
        console.log(2+5);
    }
    return sum();
}
func1();

function func2(){
    return (function sum(){
       console.log(2+5);
   })
    
}

func2();

From func1, the output is 7. But from func2, nothing is there in the console. What is the difference in both functions as both are returned from the function? Why did one get invoked and another didn't?

2

There are 2 answers

0
J. Vas On BEST ANSWER

From func1, the output is 7. But from func2, nothing is there in the console. What is the difference in both functions as both are returned from the function? Answer the difference between both is, the first one's return statement calls the the sum function.

In the second one the function's definition is returned hence it's defined but not called resulting into no output.

0
Nina Scholz On

func2 returns a function and after calling it, you get the result.

function func1() {
    function sum() {
        console.log(2 + 5);
    }
    return sum();
}

func1();

function func2() {
    return (function sum() {
        console.log(2 + 5);
    });
}

func2()();            // call function
console.log(func2()); // see function declaration