skip to Main Content

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

Answers


  1. 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
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search