Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about a function returning a function in java script

Tags:

javascript

function a(){
   function b(){
      alert("hi");
   }
   return b();
}
function c(){
   var d = a();
}

c();

When I execute the above, I get the alert "hi". but if I do as below

function a(){
    function b(){
       alert("hi");
    }
    return b();
}
function c(){
    var d = a();
    d();
}

c();

I am expecting to see two alerts for assignment and function call statements in c();, but i get only one alert. What am I doing wrong?

like image 270
QVSJ Avatar asked Apr 11 '26 13:04

QVSJ


2 Answers

Because method a is not returning anything since a is calling b in the return statement but b is not returning anything so d is undefined whcih will cause d() to throw an error

Demo: Fiddle

function c() {
    var d = a();
    alert(d)
    d();
}

If you see the fiddle, the second alert shows undefined as the value of d

like image 159
Arun P Johny Avatar answered Apr 13 '26 02:04

Arun P Johny


You are calling an undefined function.

function a(){
    function b(){
       alert("hi");
       // no return => return undefined
    }

    // the result of b() === undefined
    return b();
}
function c(){
    // assign the result of a to variable d
    // (which is itself the result of b, which is undefined, because b has no return)
    var d = a();

    // call undefined function, this will throw an error
    d();
}

c();
like image 44
Eloims Avatar answered Apr 13 '26 04:04

Eloims



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!