HelloWorld
HelloWorld

Reputation: 11237

Return a Function within a Function

Here is an example of code I am experimenting with:

var hello = function hi(){
    function bye(){
        console.log(hi);
        return hi;
    }
    bye();
};

hello();

Here is a repl.it link

I am trying to return the function hi from my function bye. As you can see, when I console.log(hi) the value appears to present, but my return statement doesn't return the hi function. Why isn't the return statement returning the reference to hi?

Upvotes: 2

Views: 261

Answers (2)

Khalid
Khalid

Reputation: 4798

Don't make think complicated by defining a function inside another one

Define your hi function first like this for example

function hi (message) 
{ 
     console.log(message) 
}

it takes an argument and show it on the console

now let's define our bye function

function bye ()
{
     hi(" Called from the function bye ");
}

no when you call bye, you call hi at the same time

bye(); // it will show on the console the message " Called from ... " 

If you want to return a function from a function it's easy you define your hi function like this

function hi (message) 
{ 
     console.log(message) 
}

and the bye function returns the hi function like this

function bye() 
{
     return hi;
}

All you need to do now, is to call the bye function and give the argument to show in the console to what was returned , just like this

bye()(" This is a sample message "); 

Upvotes: 1

djechlin
djechlin

Reputation: 60748

You forgot to return bye.

return bye();

Upvotes: 3

Related Questions