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?

2
  • The invocation happens in the expression s(2), not in s = square!? There's no argument as well. Commented Apr 1, 2015 at 20:51
  • Getting Unhandled Error: 's' is not a function for your Case 1. Commented Apr 1, 2015 at 20:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Like delegates in C#?
I have no idea, but probably not the same thing... the point is that in Javascript a function is a type of object like any other.
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.

Comments

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

Comments

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.