eternauta
eternauta

Reputation: 51

How are functions in JavaScript treated as variables?

function b() {
   return "B";
}
function output(par){
    var l=par;
    alert(l);
}
output(b);

The result i get is:

function b() (
     return "B";
)

But when i define the variable "l" outside the function. Like:

function b() {
   return "B";
}
var l=b();
alert(l);
}

The result is "B";

How do i make the function behave like in the second case but inside the function, and why is not treating it in the same way?

Upvotes: 1

Views: 303

Answers (2)

Loda
Loda

Reputation: 31

In the first case: you send function b as a parameter into function output . In the second case: you call the funcation b using "b()",so at this time the varaible l is B other than the function itself.

Upvotes: 1

Russell Zahniser
Russell Zahniser

Reputation: 16364

When you do this:

var l = b();

...you are calling b, and assigning the result to l. If you wanted l to refer to the function object b, you would just say:

var l = b;

(Likewise, in your output() function, if you did var l = par(), it would display "B".)

Upvotes: 3

Related Questions