4

I am new to javascript and have a quick question. Say i have the following code:

function entryPoint()
{
   callFunction(parameter);
}

function callFunction(parameter)
{
   ... //do something here
   var anotherFunction = function () { isRun(true); };
}

My question is that when callFunction(parameter) is called, and the variable anotherFunction is declared, does isRun(true) actually execute during this instantiation? I am thinking it doesnt and the contents of the anotherFunction are only "stored" in the variable to be actually executed line by line when, somewhere down the line, the call anotherFunction() is made. Can anyone please clarify the function confusion?

1
  • 2
    You're right, it won't be executed in that example. Commented Apr 11, 2012 at 17:59

3 Answers 3

5

It seems the confusion is this line of code

var anotherFunction = function () { isRun(true); };

This declares a variable of a function / lambda type. The lambda is declared it is not run. The code inside of it will not execute until you invoke it via the variable

anotherFunction(); // Now it runs
Sign up to request clarification or add additional context in comments.

1 Comment

Here's the style for an "immediately executing anonymous function." var anotherFunction = ( function () { isRun(true); } )();
4

You almost described it perfectly.

anotherFunction just receives a reference to a newly created Function Object (yes, Functions are also Objects in this language) but it does not get executed.

You could execute it by calling

anotherFunction();

for instance.

Comments

1

You can write a simple test like so:

entryPoint();

function entryPoint()
{
    alert("In entryPoint");
    callFunction();
}

function callFunction()
{
    alert("In callFunction");
    var anotherFunction = function () { isRun(); };
}

function isRun()
{
    alert("In isRun");
}

​ And, the answer is no, isRun() does not get called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.