1

Case 1:

function square(x) { return x*x; }
var s = square(); // Invoking with parentheses 
console.log(square(2));
console.log(s(2));

Case 2:

function square(x) { return x*x; }
var s = square;// invoking without parentheses 
console.log(square(2));
console.log(s(2));

Functions are always supposed to be invoked with (). Then why does it return undefined in case 1 , but works fine in Case 2?

Mansi
  • 35
  • 1
  • 7

3 Answers3

3

In Case 1 you assign the return value of invoking ('calling') the square function to s. But since you didn't provide any parameters you are asking it to calculate undefined * undefined, which is NaN ("Not a Number", i.e. cannot be calculated). Then at the end where you do s(2) I assume you get an error, because s is not a function.

In Case 2 you are not calling the function, you are only assigning the function object itself to var s. This means it works when you do s(2) because s is a reference to the square function.

Anentropic
  • 32,188
  • 12
  • 99
  • 147
1

You are assigning s to the output of square() in case 1. Thus, you are passing in nothing, and assigning s to undefined.

Assign s to square, without parentheses () works because you are assigning s to the function square, and not its output.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

Here case 2 works - please check the comments for better understanding,

Case 1:

function square(x) { return x*x; }
var s = square(); // Invoking without any parameter
console.log(square(2));//Invoking the actual function here with param
console.log(s(2));//This is incorrect as s is storing the result of the `square()`. So this doesn't work
Case 2:

function square(x) { return x*x; }
var s = square;// just declaring a variable
console.log(square(2));//Invoking the actual function here
console.log(s(2));//Invoking the actual function here with param. It works here
WonderHeart
  • 678
  • 10
  • 28