0

I have three simple programs below with different outputs. I am a bit confused as to why I get a different output. What really happens when you assign a function to a variable? Does it not run unless you have parentheses (i.e. myfunction())? I'm also very confused as to how JavaScript allows the parenthesis behind a function as 'optional' when calling it. Can someone clear this up? I only know Java so this is all new territory for me.

// ------First--------------------------------
var x = 9;
function myfunction (){
  x = 3;
}
var w = myfunction;
w();
console.log(x);
//output is 3


// ---------Second -----------------------------
var x = 9;
function myfunction (){
  x = 3;
}
var w = myfunction;
console.log(x);
//output is 9


// ---------Third -----------------------------
var x = 9;
function myfunction (){
  x = 3;
}
var w = myfunction();
console.log(x);
//output is 3

1 Answer 1

4

No, it does not. A reference to a function by name is simply a reference to a value, like any other value. Without the () operator, it's not a function call.

Parentheses are not optional when calling a function except when it's being called via the new operator. Thus:

function foo() {
  console.log("hi!");
}

var otherFoo = foo; // no function call
var obj = new foo;  // function call via "new"
var x = foo();      // function call via "()"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pointy. Can you please give an example of the "new operator" and how the call would happen...

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.