I created a JavaScript object like this:
var obj = {
a: 10,
b: 20,
add: function(){
return this.a + this.b;
}
};
I executed the function as obj.add
and it returns the whole function as string a like this:
function(){
return this.a + this.b;
}
But later, I tried to call the function again, including the parentheses, like `obj.add()` and it returns the value `30`. I couldn’t figure out why I get such a different output upon calling the function with `obj.add` and with `obj.add()`. What is the main difference between calling an object’s function with parentheses and without parentheses?
Without parentheses, the function name is used as the pointer of the function. The name of a function is the pointer of the function. At this time, the result of the function is not obtained, because the function body code will not be run.
When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.
It means you can call a function without parentheses if that function is no parameters. otherwise you need to include parentheses if it have parameters.
Without parentheses you're not actually calling the function. A function name without the parentheses is a reference to the function. We don't use the parentheses in that code because we don't want the function to be called at the point where that code is encountered.
Without parentheses, you're retrieving a reference to the function, you are not calling (executing) 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;
You didn't execute the function with obj.add
, you only looked it up in the object and the environment you're in happened to render the function as a string. You execute it by adding the parentheses.
Without the parenthesis you're not really calling anything, nor are you returning anything, it's just a reference !
I'm guessing you did something like this
var result = ambes.add;
console.log(result);
and that doesn't call the function, it logs the actual content of the add
property, which is the function, and logging a function will log the string content of the function, not what it would return had you called it.
It's quite simple: functionName
just returns the function body, while functionName()
executes the function and returns its return value (or undefined
, if there's no explicit return). The same principle works for when a function is an object property, like you had obj.add
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With