I created a JavaScript object like this:
var obj = {
a: 10,
b: 20,
add: function(){
return this.a + this.b;
}
};
I executed the
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
.
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 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;
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.
You must use () to call a function in JavaScript.
If you do not use parenthesis, you are simply referencing the function, which can be useful in a case where you would like to pass a function to another code block for deferred execution.
In your situation, because you wish to call add right away, you should be sure to use ()
obj.add();
Calling a function requires the () because they are the function invocation operator. To execute a function you will always need to include parentheses.
When you call ambes.add
you are returning the function object itself. If you do so inside console.log()
or concatenate it onto a string JavaScript will return the function definition as a complete string which explains the first output you receive.