# Is it possible to call a function without parenthesis

I’m trying to simulate symbolic math as follows:

``````var a = 1;
var b = 2;
function c() {
return a + b;
}
var d = 3;
var e = c() * d;
``````

Is it possible to somehow call c without using parenthesis? For example, I can do the following in Ruby which is very convenient and I was wondering if it’s possible to do something similar in javascript:

``````var e = c * d; // e should equal 9
``````

Maybe something like

``````var a = 1;
var b = 2;
c = function () {
return a + b;
}
var d = 3;
var e = c * d;
``````

*not sure if you need to use “var” or “object” to declare c

haha. got excited for a sec, but that doesn’t work. running the above gives “NaN” (and it doesn’t matter whether I use var or object to declare c). Any other ideas?

You can use Mitteneague’s script if you call the function c when you define it-

var a = 1;
var b = 2;
var c = (function () {
return a + b;
})()

var d = 3;
var e = c * d;

Thanks mrhoo. That works but doesn’t help my end goal, which is to be able to change “a” or “b” and have “e” change as a result. I believe your solution is simply storing the result of the function into “c” instead of the function itself. For example:

``````var a = 1;
var b = 2;
var c = (function () {
return a + b;
})();
var d = 3;
var e = c * d;
a = 4;
alert(e); // needs to be 15 but is still equal to 9
``````

You can’t run a function is JavaScript without the () since without it the call has a different meaning (a reference to the function rather than running it). You are asking the equivalent of how to stand up without placing your feet on anything. The () is how JavaScript knows to run the function.

You’ll need to use objects to achieve what you’re after.
With the valueOf property, we can provide the value to return when used in maths.

``````
var a = 1;
var b = 2;
var c = {
valueOf: function () {
return a + b;
}
};
var d = 3;
var e = {
valueOf: function () {
return c * d;
}
};
// When c or e are used by themself, you have to cast them as a number.
// All other cases are fine, e.g., c + 0 will equal the value of c
a = 4;
alert(e + c - b); // 22

``````

That’s nice. Let’s make a little step further:

``````
Function.prototype.valueOf = function() {
return this();
}
Function.prototype.toString = function() {
return this.valueOf().toString();
}

var a = 11;
var b = 22;
var c = function () { return a + b }