user9525655
user9525655

Reputation:

How to run a function inside of a function in JavaScript

I'm having a small issue on running a function inside of a function. Hope u guys can guide me.

<html>
<body>

<p id="demo"></p>

<script>
function myFunction()
{
    function play(a, b)
    {
        document.getElementById("demo").innerHTML = a * b;
    }
}

myFunction().play(2,3);

</script>
</body>
</html>

Upvotes: 0

Views: 112

Answers (4)

Ele
Ele

Reputation: 33726

You can't do this because that function play only exists within the function myFunction and everything outside of it won't be able to execute it.

An alternative is to return an object with a property called play whose value is the function you need to execute.

function myFunction() {
  return {
    play: function(a, b) {
      document.getElementById("demo").innerHTML = a * b;
    }
  }
}

myFunction().play(2, 3);
<p id="demo"></p>

Upvotes: 0

Isaac
Isaac

Reputation: 11805

To keep with your current usage, try this:

function myFunction()
{
    return {
        play: function(a, b)
        {
            document.getElementById("demo").innerHTML = a * b;
        }
    }
}

myFunction().play(2,3);

Upvotes: 3

Nicholas Porter
Nicholas Porter

Reputation: 2951

You will not be able to access the play function where you are currently invoking. The play function is out of scope.

function myFunction()
{
    function play(a, b)
    {
        document.getElementById("demo").innerHTML = a * b;
    }

    play(2,3);
}

myFunction()

This should work for you

Upvotes: 0

J Livengood
J Livengood

Reputation: 2738

So what you've done with myFunction is nested a 'private' function play inside so the outside cannot call it. So you can either return the inner function or call play inside of function like and only call myFunction:

function myFunction(a, b) {
    function play(a, b) {
        document.getElementById("demo").innerHTML = a * b;
    }
    play(a, b);
}
myFunction(2,3); // will set innerHTML of demo to a*b

Or remove the nesting and just have

function play(a, b) {
  document.getElementById("demo").innerHTML = a * b;
}
play(2,3);

Upvotes: 0

Related Questions