I'm trying to learn JavaScript but couldn't understand the difference between the following lines of code.
var f = myfunction;
var k = myfunction();
function myFuncton()
{
alert("hello world");
}
Since we can't do stuff like this in a managed language like C#. But I have seen so many JavaScript code examples where a function is assigned to a variable without open and close parenthesis before semicolon(;) and then the same function is assigned to another variable with open and close parenthesis as shown in the code above. What is the difference between these two assignments and why do we do that in JavaScript?
2 Answers 2
Parentheses in an assignment like this:
var k = myfunction();
mean that what's being assigned to k is not the function itself, but rather the result of calling the function — the function's return value, in other words.
Without the parentheses, then you are indeed assigning a reference to a function to some variable:
var f = myfunction;
After doing that, it'll be possible to call the function by either name:
f(); // same as myfunction();
Functions in JavaScript are just a special type of object, but they really are just objects in most ways. They can have properties, and references to them can be passed around exactly in the same way one passes around references to objects.
What makes a function special is that you can call it. A reference to a function followed by () (or () with arguments) is a function call no matter where that reference came from. That's why an assignment of a function call to a variable, or passing a function reference as an argument in a call to some other function, is useful.
2 Comments
var f = myfunction;
This creates a new variable f which refers to myfunction.
var k = myfunction();
This creates a variable k which is assigned the value that results after calling and executing myfunction().
public delegate int OperationDelegate(int p); public class MyClass { private int Square(int p) { return p*p; } public void Run() { OperationDelegate func; func = Square; func(10); func = i => i*100; func(10); } }