-2

I just had a quick question about assigning a mathematical operator to a JavaScript variable.

So I have a variable called mathFunction like below...

var Mathfunction;

If I want to apply an actual mathematical operator would I just do something like this?

var Mathfunction = +;  Or var Mathfunction = '+';

Any advice for this would be greatly appreciated!

2 Answers2

0

You can't do that, at least not meaningfully. The firs option you posted throws a SyntaxError.

You could do var Mathfunction = '+'; and eval() it, but don't do that - eval() is very unsafe. The real question is: why do this? If you are building a parser or logic engine, there are better ways to go about this.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • I am trying to create a math game. – user2793503 Feb 01 '14 at 06:24
  • *"`eval()` is very unsafe."* No it's not. It's *how it is used* that *can* make it unsafe. If you have full control over the input, it is not unsafe. – Felix Kling Feb 01 '14 at 07:34
  • @FelixKling I agree that it is how it's used that can make it unsafe, but it's complicated. You need full control *and* no errors in your logic or validation of input. `eval('2+2')` is perfectly safe. `eval(foo+Mathfunction+bar)` may be safe or may not be, but doing it in a way that you can be sure that it is safe is extremely difficult and prone to errors. Avoiding `eval()` in pretty much every language whenever possible is a best practice, for good reason. – elixenide Feb 01 '14 at 14:34
-1

You can use the operator var Mathfunction = '+'; for math matical operation.

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34