ambes ambes - 9 months ago 42
Javascript Question

JavaScript: calling a function with out parenthesis return's whole function as string

I create a javascript Object as below code:

var obj={
a : 10,
b : 20,
add : function(){
return this.a + this.b;

i executed the function with this code
and it return the whole function as string like this:-

return this.a + this.b;

but later i try by call the function again including the parenthesis like
and it return the value 30. Here i couldn't figure out why i get such different out put upon calling the function with
? What is the main difference between calling an objects function with parenthesis and with out parenthesis Can any body help??

Answer Source

Without parentheses, you're retrieving a reference to the function.

With parentheses, you're executing the function.

function a() {
  return 2;

var b = a(); // called a, b is now 2;
var c = a; // c is referencing the same function as a
console.log(c); // console will display the text of the function in some browsers
var d = c(); // But it is indeed a function, you can call c(), d is now 2;