ttmcswg ttmcswg - 1 month ago 8
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
'2*4'
. I also tried
parseInt
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){
  this.number=x+operation+y;
  return eval(this.number);
}
console.log(calculator(1,2,"+"));
console.log(calculator(1,2,"-"));
console.log(calculator(1,2,"*"));
console.log(calculator(1,2,"/"));