Calling A Function Without Parentheses Returns Whole Function As A String
Solution 1:
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;
Solution 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.
Solution 3:
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.
Solution 4:
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
.
Solution 5:
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.
Post a Comment for "Calling A Function Without Parentheses Returns Whole Function As A String"