73

I just want to know how to call a javascript function inside another function. If I have the code below, how do I call the second function inside the first?

function function_one()
{
alert("The function called 'function_one' has been called.")
//Here I would like to call function_two.
}

function function_two()
{
alert("The function called 'function_two' has been called.")
}

4 Answers 4

120

function function_one() {
    function_two(); // considering the next alert, I figured you wanted to call function_two first
    alert("The function called 'function_one' has been called.");
}

function function_two() {
    alert("The function called 'function_two' has been called.");
}

function_one();

A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).

Sign up to request clarification or add additional context in comments.

2 Comments

what if function_one is a callable function. Such as in case of following mutation example. developer.mozilla.org/en-US/docs/Web/API/MutationObserver How can one call the function_two from within the callable function.
@SizzlingCode I'm not sure how that is any different than my code above. The reason this code works is because of "variable hoisting": scotch.io/tutorials/understanding-hoisting-in-javascript
23
function function_one() {
  function_two(); 
}

function function_two() {
//enter code here
}

Comments

5

function function_one()
{
    alert("The function called 'function_one' has been called.")
    //Here u would like to call function_two.
    function_two(); 
}

function function_two()
{
    alert("The function called 'function_two' has been called.")
}

Comments

0
function function_first() {
    function_last(); 
    alert("The function called 'function_first' has been called.");
}

function function_last() {
    alert("The function called 'function_last' has been called.");
}

function_first();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.