ttmcswg ttmcswg - 6 months ago 40
Javascript Question

How to make a function like calculate(x, y, operator)?

How to make this kind of function work? If I call it like

calculate(2, 4, '*')
it will return me a String
. I also tried
with no success, it only makes first appear in String to Number.

function calculate(x, y, operation) {
this.number = x + operation + y;
return this.number;

Answer Source

This is a basic calculator, you already wrote all the code. just missing the eval.

Note: please note that for a simple calculator, the eval can be used. Provided you don't implement this in some critical project, etc, for security reasons, but if its for some internal use or for an assignment its not that bad and quite handy.

function calculator(x,y,operation){
  return eval(this.number);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download