8

As we all know, this following will not run the a() function so the alert box will not appear

// 1st
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};

and we know that the following code will run the a() function and alert box 'A!' will appear

// 2nd
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
a(); // calling function

However, if we run following code, the a() function will be called and alert box 'A!' will also appear, just like the second code above

// 3rd
function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
var x = a(); // assigning function to new variable

QUESTION: why does this happen (on 3rd snippet)? we didn't call the a() function yet (my current understanding). Didn't we just assigning x to a() function?.

xcode
  • 1,637
  • 3
  • 16
  • 25

2 Answers2

21

Didn't we just assigning x to a() function?.

No, you assigned the returned value from a() to x.

If you don't want to call a, then do

var x = a;

and later do

x();
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
6

You're wrong. You are invoking the function:

var x = a(); // assigning function to new variable

This line of code says invoke a when you write a(). The parentheses indicate an invocation.

To assign a function to a variable you have to use just the name, such as:

var x = a;

or pass the name to a function f:

f(a)

As a counter-example you invoke it in this next line of code and pass to g not the function be the result of its execution:

g(a())
pid
  • 11,472
  • 6
  • 34
  • 63